在AJAX JSON响应中包含HTML

时间:2021-12-06 02:02:01

Brief Explanation

I have a form that is currently being loaded via AJAX. Ideally I would use the jQuery load() method, however, this request is slightly more complex as I also need to retrieve individual properties instead of just one large HTML chunk.

我有一个目前通过AJAX加载的表单。理想情况下我会使用jQuery load()方法,但是,这个请求稍微复杂一些,因为我还需要检索单个属性而不是只检索一个大的HTML块。

So, my script looks something like this (simplified):

所以,我的脚本看起来像这样(简化):

$.ajax({
    url: url,
    dataType: 'json',
    success: function(data){
        // Set the width of the form
        $('.form').css({
            width: data.width
        })
        // Load the form into the popup
        $('.form').html(data.html);
    }
});

My Question

I am unsure whether including my HTML markup in the JSON response is such a good idea...

我不确定在JSON响应中包含我的HTML标记是否是一个好主意......

  1. Am I correct in thinking the above?
  2. 我是否正确思考以上内容?
  3. Are there any other alternatives?
  4. 还有其他选择吗?
  5. Will I run into limits with large chunks of html stored in a JSON request?
  6. 我是否会遇到存储在JSON请求中的大块html的限制?

Please Note

I am of course aware that I could build the markup using javascript, however, as there are several forms and all of which are quite large, it it much easier to build the form server side. Not to mention the fact it makes it much easier to debug/develop/maintain...

我当然知道我可以使用javascript构建标记,但是,因为有几种形式,并且所有形式都非常大,所以构建表单服务器端要容易得多。更不用说它使调试/开发/维护更容易......

Furthermore, my site is currently VERY javascript heavy so I would like to minimise as much of the js needed as I possibly can.

此外,我的网站目前非常重,所以我想尽量减少尽可能多的js。

1 个解决方案

#1


4  

  1. You can include the html in a json object, just make sure to escape all quotes and other special characters.
  2. 您可以在json对象中包含html,只需确保转义所有引号和其他特殊字符。
  3. You're probably better off with two requests, one that loads the html form and another that gets the data you need. This will make for cleaner, more maintainable code.
  4. 你可能最好有两个请求,一个加载html表单,另一个得到你需要的数据。这将使代码更清晰,更易于维护。

#1


4  

  1. You can include the html in a json object, just make sure to escape all quotes and other special characters.
  2. 您可以在json对象中包含html,只需确保转义所有引号和其他特殊字符。
  3. You're probably better off with two requests, one that loads the html form and another that gets the data you need. This will make for cleaner, more maintainable code.
  4. 你可能最好有两个请求,一个加载html表单,另一个得到你需要的数据。这将使代码更清晰,更易于维护。