Javascript 无法通过 jQuery ajax 发送特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8863506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot send special characters via jQuery ajax
提问by Jonathan Clark
I am developing a webpage where user is searching for files using tags. I am using jQuery Ajax to do the remote call to the API (database). It all works fine when I use non special characters like a-z but fails when using for example ???.
我正在开发一个网页,用户在其中使用标签搜索文件。我正在使用 jQuery Ajax 对 API(数据库)进行远程调用。当我使用像 az 这样的非特殊字符时一切正常,但在使用例如 ??? 时失败。
On the serverside I am using PHP. I print the tag to see if it "arrives" and all a-z works fine but the ??? is not displaying at all. They seem to not "arrive".
在服务器端,我使用 PHP。我打印标签以查看它是否“到达”并且所有 az 都可以正常工作,但是 ??? 根本不显示。他们似乎没有“到达”。
What can be wrong?
有什么问题?
This is my jQuery code:
这是我的 jQuery 代码:
var tags = $('#tags').val();
$.ajax ({
type: "POST",
url: base_url + "search",
data: "tags=" + tags + "&limit=" + limit,
beforeSend: function (html) {
$("#search_results").html("Searching for files...");
},
success: function (html) {
$("#search_results").html(html);
},
error: function (html) {
$("#search_results").html('Something went wrong!');
}
});
This is my server side code:
这是我的服务器端代码:
echo ($_POST['tags']);
I search and looked at related questions about this here on SO but non helped me unfortunately.
我在 SO 上搜索并查看了与此相关的问题,但不幸的是没有帮助我。
UPDATE
更新
Using this solved it! Works fine now.
用这个解决了!现在工作正常。
{tags: encodeURIComponent(tags), limit: limit}
回答by Vadim Gulyakin
Data (tags) must be encoded before sending it to server using encodeURIComponent()
数据(标签)必须在使用 encodeURIComponent() 将其发送到服务器之前进行编码
回答by satya prakash
Below code is working fine for sending & and "" or any special characters via ajax call:
下面的代码适用于通过 ajax 调用发送 & 和 "" 或任何特殊字符:
specialChar1= "JΛ?KE#2@#*&($^@%#*@#%))*$&@*(""" ;
specialchar2 ="??&!!--##";
url = "/get/" + encodeURIComponent( specialChar1) +"/"+ encodeURIComponent ( specialchar2 )
回答by Anurag U R
You can achieve this by using JSON object.
您可以通过使用 JSON 对象来实现这一点。
For example:
例如:
[{"AttributeId":"4035","Value":"Street & House"}]
or, you can use URLencode
before post.
或者,您可以URLencode
在发布前使用。