AJAX请求替换整个页面标记

Entire page markup is replaced on AJAX request

本文关键字:请求 替换 AJAX      更新时间:2024-04-11

当我在js.erb模板中调用函数时,它会替换整个页面,而不仅仅是我指示的div。有人能帮忙吗?

删除.js.erb

$('div.mini-basket-wrapper').html("<%= j(render 'shop/baskorder/mini_basket') %>");

#This replaces the page completely
$('#basket-info').load(document.write(basket_text()));

视图

<div id="basket-info">
  <div id="basket-amount">
    <div class='mini-basket-icon'>
     <%= image_tag 'shop/icons/basket.svg', alt: '' %>
    </div>
    <script type='text/javascript'>
      document.write(basket_text());
    </script>
  </div>
</div>

JS

    function fc_basket_text_from_cookie(empty_text, normal_text)
{
  var basket = readCookie('bk');
  if (basket)
  {
    var parts = decodeURIComponent(basket.replace(/'+/g, '%20')).split('|')
    if (parseInt(parts[1]) == 0)
      return normal_text.replace(/##VALUE##/g, parts[0]).replace(/##ITEMS##/g, parseInt(parts[1]));
      // return empty_text
    else
      return normal_text.replace(/##VALUE##/g, parts[0]).replace(/##ITEMS##/g, parseInt(parts[1]));
  } else {
    return '';
  }
}
var emptyBasketHTML = "<span class='header_text'>Items in basket: 0 Total: &#163;0.00</span>";
function basket_text(){
  var populated = "<span class='header_text'>Items in basket: ##ITEMS##</span><span class='header_text'>Total: ##VALUE##</span>";
  //populated += "<input type='submit' value='Checkout' name='commit' class='go_botton header-checkout-button'>"
  return fc_basket_text_from_cookie(emptyBasketHTML,populated);
}

阅读此处:使用document.write.

页面加载完成后,文档将关闭。试图在其中写入文档.write将导致内容被擦除。

此外,.load()函数用于从服务器加载数据。我相信你想要.html函数。

[未测试]更改线路$('#basket-info').load(document.write(basket_text()));

$('#basket-info').html(basket_text());

感谢您的输入。意识到我做错了什么,决定在我的js文件中添加一个关于成功的ajax:

$(document).on('ajaxSuccess', function(){
    $('#basket-amount-info').html(basket_text());
});

添加了此id #basket-amount-info以在视图中包含脚本。