在Ajax POST和JSON中发送特殊字符 [英] Sending special characters in Ajax POST and JSON
问题描述
@已解决
正如James M. Lay解释的那样,我应该将内容类型从application/x-www-form-urlencoded
更改为application/json
As explained by James M. Lay, I should change my content-type from application/x-www-form-urlencoded
to application/json
暗示一个错误,因为似乎只有UrlEnconded类型在服务器端(至少在PHP中)生成POST数组.因此,我必须更改服务器脚本中请求的接收/处理方式
it implied in an error because it seems that only UrlEnconded types generates POST arrays in server side (at least in PHP). So I had to change the way I receive/deal with the request in my server script
$json = file_get_contents('php://input'); //yes. php://input
if($json) $params = json_decode($json,true);
else $params = $_POST;
我还必须对Javascript代码进行一些更改,以检查内容类型并生成不同的字符串.如果是JSON,我只需使用JSON.stringify
I also had to make a few changes in the Javascript code to check the content-type and generate different strings. If it's JSON I just use JSON.stringify
//string to use in the 'send' method
this.getParametersString = function(){
if(this.contentType == 'application/json'){
return JSON.stringify(this.parameters);
}else{}
}
我有一个问题
I got a question
我正在构建一个函数,该函数接收参数以编写参数列表并通过POST发送
I`m building a function that receive parameters to write a list of parameters and send it by POST
问题是我们无法发送特殊字符,例如+
The problem is that we can't send special characters, such is +
所以我尝试使用功能encodeURIComponent
将它们编码为URI友好字符串.
So I tried to use the function encodeURIComponent
to encode them to a URI friendly string.
还有另一个问题:如果接收到的参数是一个对象,我将遍历属性,检查它是另一个对象还是字符串,如果是对象,则再次循环,否则对其进行编码.
There comes another problem: if the parameter received is an object, I am loop through the attributes, checking if it is another object or a string, if it is an object, loop again, otherwise encode it.
但是它返回一个编码字符串的对象.我必须使该对象成为发送它的字符串,为此,我使用JSON.stringify
.它解码编码的字符串.因此%2B
再次变为+
,并且不会通过POST发送到服务器.
But it is returning an object of encoded strings. I have to make the object become a string to send it, and for that purpose I use JSON.stringify
. It decodes the encoded string. So %2B
becomes +
again and It is not sent to the server via POST.
我先使用stringify
和encodeURIComponent
,它将生成不应被编码且字符串不是写得好的JSON的符号,例如和{}
on the other hand If I use stringify
first and the encodeURIComponent
it generates signs like " and { } that shouldn't be encoded and the string is not a well written JSON
那你怎么样?这是不使用jQuery的方法吗?我必须构建自己的stringify函数吗?!
How do you that? Is that a way without using jQuery? Do I have to build my own stringify function?!
推荐答案
im使用以下内容,但我没有任何问题
im using the following and i have no issues
encodeURIComponent(JSON.stringify(object_to_be_serialised))
这篇关于在Ajax POST和JSON中发送特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!