简体   繁体   中英

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

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

pls tell me what the reason and how can I solve it?

parsing code 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. You'll save yourself a lot of trouble that way. http://php.net/manual/en/function.json-encode.php

nl2br() does not replace the line breaks, only inserts <br> before them.

As such, \\n is being returned and therefore creating invalid JSON.

You should use json_encode() when creating JSON strings. For simplicity, you could simply use it on 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. Then you will have to replace each \\r\\n occurences by <br> tags.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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