2

i have a a php page to retrieve the new messages from database and send report about them in json if new message its body will contain no html except some inserted brs (<br/>)

when the json is received in javascript i find all brs coverted from this (<br/>) to (<br\/>) so its job disabled

when i tried to do with other html like

<?php
$a="<html><br/></html>";
echo $a,"\n";
echo "Normal: ", json_encode($a), "\n";
echo "Tags: ",   json_encode($a,JSON_HEX_TAG), "\n";
echo "Apos: ",   json_encode($a,JSON_HEX_APOS), "\n";
echo "Quot: ",   json_encode($a,JSON_HEX_QUOT), "\n";
echo "Amp: ",    json_encode($a,JSON_HEX_AMP), "\n";
echo "All: ",    json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), "\n\n";
?>

the out put was like this

<html><br/></html> 
Normal: "<html><br\/><\/html>"
Tags: "\u003Chtml\u003E\u003Cbr\/\u003E\u003C\/html\u003E"
Apos: "<html><br\/><\/html>"
Quot: "<html><br\/><\/html>"
Amp: "<html><br\/><\/html>"
All: "\u003Chtml\u003E\u003Cbr\/\u003E\u003C\/html\u003E"

its my first time to send html in json previously always data (plain text). what has caused this and what can i do to solve this problem??????????


thanks to all those who tried to help because i need it quickly i used this

$("selector").html(result.messageBody.replace("\/","/"));
ahmedsafan86
  • 1,776
  • 1
  • 26
  • 49
  • 1
    Why would you send HTML as JSON in the first place? HTML has it's own structure for its data, no need to use yet another data structure on top of it. – Björn Feb 02 '11 at 09:54
  • i'm sending many parts [sender_name ,mobile_number, sent_time, message_body] – ahmedsafan86 Feb 02 '11 at 14:20
  • [The `/` must be escaped in JSON.](http://json.org/) But how do you send the request and process the response that this is a problem for you? – Gumbo Feb 02 '11 at 14:24

1 Answers1

3

In JavaScript Object Notation (JSON) slashes are escaped with backslashes, so <br\/> is valid JSON, <br/> isn't.

If you want to work with JSON values you have to decode it:

result = JSON.parse(result);
// or
result = eval(result); // simple but maybe unsecure!
Floern
  • 33,559
  • 24
  • 104
  • 119
  • what is JSON.decode?? which extension jquery?? i'm receiving the data as json with jquery $.post("url",{params},callback,"json"); – ahmedsafan86 Feb 02 '11 at 13:22
  • 1
    Okay, it's JSON.parse(). Have a look at this: http://stackoverflow.com/questions/4846069/echod-php-encode-json-called-via-ajax-returns-what-exactly/4846088#4846088 . I don't know how to handle JSON in jQuery. – Floern Feb 02 '11 at 13:52
  • More correctly, it's a **string** in JSON that's backslash-escaped, not the actual JSON code itself. – zanlok Feb 02 '11 at 13:56