简体   繁体   English

在Ajax响应文本中发送json字符串和html数据-如何?

[英]Sending json string along with html data in ajax response text - How to?

For small amounts of textual info ( Control Messages ) I send what I call bullets (Same syntax as HTML comments ) along with my page during ajax calls. 对于少量文本信息(控制消息),我在ajax调用期间将所谓的项目符号(与HTML注释相同的语法)与页面一起发送。 For example 例如

<!--Control Message--><html> all my page here</html>

I then parse the "Bullet" out before rendering the page...even though I don't really have to. 然后,我在渲染页面之前将“子弹”解析出来……尽管我并不是必须这么做。

For more data, say 5 variables, I plan on json_encoding it...and sending it with the page as well. 对于更多数据,说5个变量,我计划对其进行json_encoding ...并与页面一起发送。

How are others demarcating and extracting the structured data / json strings from html. 其他人如何从html划界和提取结构化数据/ json字符串。 I could just put it in a "bullet" like below and extract it out...but my guess is there is a more "proper" way to do this. 我可以将其放在下面的“项目符号”中,然后将其提取出来...但是我猜想还有一种更“正确”的方法可以做到这一点。

<!--json string here--><html> all my page here</html>

If you are passing this via AJAX, just embed the HTML in the JSON and parse that JSON as a whole: 如果要通过AJAX传递此代码,只需将HTML嵌入JSON并将该JSON解析为一个整体:

{
    "html":"<html>...</html>",
    "other_data":...,
    "some_more_data":...
}

//access it later:
data.html
data.other_data
data.some_more_data

If this data loaded with the page, store the data in a variable instead: 如果此数据与页面一起加载,则将数据存储在变量中:

<html>
    <head>
        <script>
            var data = <?= json_encode($data) ?>;

If the data is contextual with the HTML, it would be good to send them as data tags within the HTML? 如果数据与HTML关联,那么将其作为HTML中的数据标签发送会很好吗?

<html data-value="{name:value}">
    <body>
        <div data-div="{name:value}">
    </body>
</html>

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

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