Sending HTML Code Through JSON

前端 未结 7 1061
暗喜
暗喜 2020-11-30 07:07

I\'ve got a php script which generates HTML content. Is there a way to send back that HTML content through JSON to my webpage from the php script?

相关标签:
7条回答
  • 2020-11-30 07:45

    Just to expand on @T.J. Crowder's answer.

    json_encode does well with simple html strings, in my experience however json_encode often becomes confused by, (or it becomes quite difficult to properly escape) longer complex nested html mixed with php. Two options to consider if you are in this position are: encoding/decoding the markup first with something like [base64_encode][1]/ decode (quite a bit of a performance hit), or (and perhaps preferably) be more selective in what you are passing via json, and generate the necessary markup on the client side instead.

    0 讨论(0)
  • 2020-11-30 07:55

    All these answers didn't work for me.

    But this one did:

    json_encode($array, JSON_HEX_QUOT | JSON_HEX_TAG);
    

    Thanks to this answer.

    0 讨论(0)
  • 2020-11-30 07:56

    Yes, you can use json_encode to take your HTML string and escape it as necessary.

    Note that in JSON, the top level item must be an array or object (that's not true anymore), it cannot just be a string. So you'll want to create an object and make the HTML string a property of the object (probably the only one), so the resulting JSON looks something like:

    {"html": "<p>I'm the markup</p>"}
    
    0 讨论(0)
  • In PHP:

    $data = "<html>....";
    exit(json_encode($data));
    

    Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/

    0 讨论(0)
  • 2020-11-30 07:59

    You can send it as a String, why not. But you are probably missusing JSON here a bit since as far as I understand the point is to send just the data needed and wrap them into HTML on the client.

    0 讨论(0)
  • 2020-11-30 08:03

    All string data must be UTF-8 encoded.

    $out = array(
       'render' => utf8_encode($renderOutput), 
       'text' => utf8_encode($textOutput)
    );
    
    $out = json_encode($out);
    die($out);
    
    0 讨论(0)
提交回复
热议问题