我怎样才能把双引号字符串内内PHP的AJAX JSON响应? [英] How can I put double quotes inside a string within an ajax JSON response from php?
问题描述
我收到来自服务器的Ajax请求的JSON响应。这样,它的工作原理:
{一个:1,B:你好小猫'}
但我没有把周围的双引号成功的的小猫的。
当我转换到\ X22在Ajax响应,它仍然是PTED为跨$ P $通过JavaScript和我不能解析JSON。
我应该也难逃\和反向转义后(这是可能的)?
如何做到这一点?
编辑:的我不知道,如果我EX pressed得好:我想B的内该字符串后的解析:
您好小鹰
如果有必要我也可以解析后添加一个额外的步骤来转换B,但我想这是没有必要的,还有一个更优雅的方式,所以这是自动发生的?
EDIT2:的Ajax页面是由PHP产生。我试过几件事情立即创建b的值,所有结果页面上的JSON解析错误:
$ B =你好小鹰';
//无1:
// $ B = str_replace函数('',\ X22,$ B);
//或没有2:
// $ B =和addslashes($ B);
//或没有3:
$ B = str_replace函数('','\',$ B);
回声{一个:1,B:'。$ B'}';
EDIT3:的这个解决方案最终作品:
$ B =你好小鹰';
$ B = str_replace函数('','\\,$ B);
回声{一个:1,B:'。$ B'}';
只是一个反斜杠转义:
> JSON.stringify({A:5,B:是小鹰威猛奇'})
{一:5,B:一个\小鹰\威猛奇}
> JSON.parse({一:5,B:一个\\猫咪\\威猛奇})
目的
答:5
B:小猫咪威猛奇
__proto__:对象
JSON解析器识别 \
里面的双引号的字符串作为一个双引号,需要注意的是,在第二个例子中,双反斜线是必要的,因为有一个Javascript解析器通,然后又JSON解析器通。
I receive a JSON response in an Ajax request from the server. This way it works:
{ "a" : "1", "b" : "hello 'kitty'" }
But I did not succeed in putting double quotes around kitty.
When I convert " to \x22 in the Ajax response, it is still interpreted as " by JavaScript and I cannot parse the JSON.
Should I also escape the \ and unescape later (which would be possible)?
How to do this?
Edit: I am not sure if i expressed it well: I want this string inside of "b" after the parse:
hello "kitty"
If necessary I could also add an additional step after the parse to convert "b", but I guess it is not necessary, there is a more elegant way so this happens automatically?
Edit2: The ajax page is generated by php. I tried several things now to create the value of b, all result in JSON parse error on the page:
$b = 'hello "kitty"';
// no 1:
//$b = str_replace('"',"\x22",$b);
// or no 2:
// $b = addslashes($b);
// or no 3:
$b = str_replace('"','\"',$b);
echo '{ "a" : "1", "b" : "' . $b . '"}';
Edit3: This solution finally works:
$b = 'hello "kitty"';
$b = str_replace('"','\\"',$b);
echo '{ "a" : "1", "b" : "' . $b . '"}';
Just escape it with a backslash:
> JSON.stringify({"a": 5, "b": 'a "kitty" mighty odd'})
{"a":5,"b":"a \"kitty\" mighty odd"}
> JSON.parse('{"a":5,"b":"a \\"kitty\\" mighty odd"}')
Object
a: 5
b: a "kitty" mighty odd
__proto__: Object
JSON parsers recognize \"
inside double-quoted strings as a double quote. Note that in the second example, the double-backslash is needed because there's a Javascript parser pass, then another JSON parser pass.
这篇关于我怎样才能把双引号字符串内内PHP的AJAX JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!