简体   繁体   中英

Sending html to Javascript from PHP via JSON obejct

I'm sending some data from php through ajax to jquery.

If $content="ABC"; everything is OK. I get alert with ABC.

If $content="<div>ABC</div>"; then Houston has a problem. Nothing happens at all.

Here is PHP code

$json = json_encode(array("content" => $content));
echo $json;

And this is Jquery

 $('#'+pic_type+'_form_n_'+pic_number).ajaxSubmit({
 success: function(responseimage){
 result = jQuery.parseJSON(responseimage);
 alert(result.content);

Any ideas ?

UPDATE! I've removed jQuery.parseJSON so that line has only this code

result = responseimage;

And now I get the result in alert. The result is the following

{"content":".<div>ABC&lt;\/div&gt;."}</div>

So we can see that JSON is not created well. I;ve tried utf8_encode and trim , but they do nothing to the result. result is strange.

PHP (and JSON) code seems fine, provided that the variable $content actually has any content. Else the PHP script will fail and there's your problem.

Did you define the dataType as "json" in the AJAX request?

$.ajax({
    url: 'json.php',
    dataType: 'json',
    success:function(data){
        console.log(data);
    }
});

I think you just need to utf8_encode your response before doing json_encode . Just change this :

$content = utf8_encode("<div>ABC</div>");

您以某种方式传递了无效的json-请把您的原始响应放入JSONLint中 ,它将告诉您什么地方不对。

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