从jQuery ajax response html更新多个div

时间:2009-06-08 04:07:57

标签: jquery asp.net-mvc ajax

我在asp.net mvc购物车中有一个页面,允许您输入优惠券并显示订单摘要以及其他页面内容。我想有一个更新按钮,它将验证优惠券代码,报告任何错误,并通过jQuery ajax更新页面上的订单摘要。

我知道我可以通过创建表单和部分视图并在jQuery提交中使用target属性来实现。但是,我以为我可以做以下事情:

var options
{
  success: function (responseHtml) // contains the entire form in the response
  {
    // extract sub-sections from responseHtml and update accordingly

    // update <div id="coupon"> with coupon div from responseHtml
    // update <div id="order-summary> with order summary div from responseHtml
  }   
}
$('#my-form').ajaxSubmit(options); // submits the entire form

这里的优点是我不必进行整页刷新或创建包含所有需要更新的区域的局部视图。有没有一种合适的方法可以通过jQuery ajax做到这一点?

4 个答案:

答案 0 :(得分:8)

James Skidmore's answer更清晰的解决方案,尽管这个想法是相同的:

var $holder = $('<div/>').html(responseHtml);
$('#coupon').html($('#coupon', $holder).html());
$('#order-summary').html($('#order-summary', $holder).html());

答案 1 :(得分:3)

jQuery taconite插件是针对这些场景制作的。它是一个透明的插件,拦截ajax响应。例如,如果您的应用程序返回以下XML:

<taconite> 
    <replace select="#promotion"> 
        <div>Thank you for your order!</div> 
    </replace> 

    <remove select="#emptyMsg, .preOrder" /> 

    <append select="#cartTable tbody"> 
        <tr><td>1</td><td>Dozen Red Roses</td><td>$18.99</td></tr> 
    </append> 

    <replaceContent select="#cartTotal"> 
        $18.99 
    </replaceContent> 
</taconite> 

它会:

  • 将“推广”div替换为“谢谢”消息
  • 从购物车中删除“emptyMsg”行并删除“preOrder”类
  • 的所有元素
  • 使用订单的数量,描述和金额向购物车添加一行
  • 使用新的购物车总数
  • 更新“cartTotal”元素

(来自Taconite网站的示例)

答案 2 :(得分:1)

如果我理解正确,服务器响应将包含一个HTML页面,您希望从中提取特定元素并相应地更新当前页面的相应元素。

可能有更好的方法可以做到这一点,但这是我想到的。还要确保将提到的ID切换到类:

// In your success function shown in your question:
if ($('#ajaxResponse').length > 0)
{
  $('#ajaxResponse').remove(); // Remove previous AJAX response if it exists
}
$('body').append('<div id="ajaxResponse" style="display: none;">'+responseHtml+'</div>');
$('.coupon:first').html($('#ajaxResponse .coupon').html());
$('.order-summary:first').html($('#ajaxResponse .order-summary').html());

答案 3 :(得分:0)

你可以在一次调用中通过使用ajax(),get()或post()方法获取整个html页面作为响应并在成功回调函数中分割出部分内容,或者如果如果您希望单独更新页面的每一部分,可以使用jQuery's load() method

相关问题