简体   繁体   English

带有一些html标记的JSON字符串在解析时失败

[英]JSON string with some html tag failing at parse

I am taking user input sending it to server using jQuery ajax...after inserting user values in database I am sending response back to client as JSON string as following 我正在接受用户输入使用jQuery ajax将其发送到服务器...在数据库中插入用户值后我将响应作为JSON字符串发送回客户端如下

echo '{"success":"true","data":"'.nl2br($a).'","type":"text"}'; echo'{“success”:“true”,“data”:“'。nl2br($ a)。'”,“type”:“text”}';

as user input can contain new line, I am using nl2br so that all new line characters are converted to <br> and also know that JSON doesnt support multi line, thats why I am using nl2br....but parsing is failing at client side 由于用户输入可以包含新行,我使用nl2br以便将所有新行字符转换为<br>并且还知道JSON不支持多行,这就是为什么我使用nl2br ....但解析在客户端失败侧

pls tell me what the reason and how can I solve it? 请告诉我原因是什么,我该如何解决?

parsing code var obj = jQuery.parseJSON(data); 解析代码var obj = jQuery.parseJSON(data);

echo json_encode(array("success"=>"true","data"=>$a,"type"=>"text")

Use the php function json_encode rather then trying to set the encoding yourself. 使用php函数json_encode而不是尝试自己设置编码。 You'll save yourself a lot of trouble that way. 你会以这种方式为自己省去很多麻烦。 http://php.net/manual/en/function.json-encode.php http://php.net/manual/en/function.json-encode.php

nl2br() does not replace the line breaks, only inserts <br> before them. nl2br()不替换换行符,只在它们之前插入<br>

As such, \\n is being returned and therefore creating invalid JSON. 因此,返回\\n ,因此创建无效的JSON。

You should use json_encode() when creating JSON strings. 在创建JSON字符串时应该使用json_encode() For simplicity, you could simply use it on data : 为简单起见,您可以简单地在data上使用它:

echo '{"success":"true","data":' . json_encode(nl2br($a)) . ',"type":"text"}';

You should be using json_encode, wich will generate a JSON string that contains \\r\\n for line breaks. 您应该使用json_encode,它将生成一个包含\\r\\n的JSON字符串,用于换行符。 Then you will have to replace each \\r\\n occurences by <br> tags. 然后你必须用<br>标签替换每个\\r\\n

echo str_replace('\r\n','<br>', json_encode(array("success"=>"true","data"=>$a,"type"=>"text")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM