我有一个数据响应,包括两个完全独立的部分,从一个演示的角度来看,但它们在服务器端逻辑连接,因此在一个AJAX调用中更有效地生成。这两个部分必须填充两个单独的div。我的问题是,最佳方法是什么?
OPTION1:在服务器端生成响应:
<div id="first_section">
...
</div>
<div id="second_section">
...
</div>
将响应加载到虚拟div中,如$('#dummydiv')。html(response),然后提取单个部分,如$('#first_section).html()和$('#second_section).html ()并使用它们的返回字符串来填充目标div,如
$('#target_div1').html( $('#first_section).html());
$('#target_div2').html( $('#second_section).html());
选项2:编写JS以将响应作为一个大字符串处理,使用一些正则表达式来解析并返回两个单独的部分作为两个单独的字符串,分配给目标div的.html()。
选项3:有两个单独的AJAX调用,每个div一个(由于服务器端计算非常连接,因此是昂贵的重复选项)。
选项4:有任何建议吗?
由于这是我需要在应用程序中持续执行的操作,因此正确的方法非常重要。任何评论或不同的方法ALTOGETHER将不胜感激。
UPDATE :响应是演示文稿(服务器端为数据生成的标记很多)而不是数据密集型。我认为JSON是一个错误的选择,因为它需要在客户端生成标记。
答案 0 :(得分:3)
一种方法是返回与您要填充的元素具有相同ID的html段。您可以从响应中创建jQuery对象,然后使用find
获取每个部分所需的html。这个响应jQuery对象永远不会插入到DOM中。
<div> <!--- root element wrapper, could even be full page which is excessive but works -->
<div id="first_section">
<!--- new content -->
</div>
<div id="second_section">
<!--- new content -->
</div>
</div>
然后是ajax:
$.get('path/to/server/', data, function(response){
/* create object from response*/
var $newHtml=$(response);
/* search response object for proper html to insert*/
$('#first_section').html( $newHtml.find('#first_section').html());
/* match for second section*/
})
答案 1 :(得分:2)
您应该将结果作为JSON而不是纯文本返回。这样,您可以返回具有2个属性的数组或对象。
答案 2 :(得分:2)
在这样的事情中很难说什么选择更好,或者是正确的选择。 但是,你可以这样做:
response =
<div class="_section1"></div> <div class="_sectio2"></div>
$getJSON("url", {data=""}, function(result){
var $html = result;
$('#target_div1').html($html.find("._section1")[0]);
$('#target_div2').html($html.find("._section2")[1]);
});