Passing Value Including Spaces on Ajax Call

后端 未结 3 1066
眼角桃花
眼角桃花 2021-01-18 15:04

Trying to pass spaces along with ajax call.

\'word\' is been passed the same as \'word \' i believe so.

On the other hand two words need to be send completel

相关标签:
3条回答
  • 2021-01-18 15:38

    The simplest way, I think, is to encodeURIComponent string in javascript before sending xmlhttprequest, and then urldecode it in PHP

    0 讨论(0)
  • 2021-01-18 15:50

    I know this is an old question, but I'd like to point out that the accepted answer is suggesting a function that is deprecated as of JavaScript version 1.5.

    Instead, you should use either encodeURI() or encodeURIComponent() for sending spaces and other special characters.

    var param = encodeURIComponent("word second "); 
    console.log(param); // outputs 'word%20second%20'
    

    PHP on the other end will handle the decoding automatically. You should trim server side, as client side code can be edited by users to circumvent trimming, potentially causing bugs or vulnerabilities.

    0 讨论(0)
  • 2021-01-18 15:52

    To allow a parameter to include spaces, etc. you will want to use the javascript escape() [W3Schools] function.

    escape( 'hello world ' ) = 'hello%20world%20';
    

    The handling on the PHP side will automatically decode/unescape the parameter, restoring the spaces (along with any other characters which cannot be part of a parameter's value when sent through AJAX, such as "=" or "&".

    Within PHP, if you are wanting to strip off any leading or trailing spaces, you can use the PHP trim() [PHP.net] function.

    trim( 'hello world ' ) = 'hello world';
    
    0 讨论(0)
提交回复
热议问题