开发者

jQuery ajax request and inline javascript

Hello fellow Stackoverflow users,

I have a page which does a AJAX request to update the shoppingcart. The problem is that the cart has some inline javascript which breaks the page on the ajax request.

The following is the ajax request i use:

    $.ajax({
        url: "Default.aspx?ID=5&productid=PROD147&cartcmd=add",
        success: function () {
            $.ajax({
                url: "Default.aspx?ID=5",
                dataType: "html",
                cache: false,
                success: function(html){
                    $(html).remove('script');
                    console.log(html);
                    var ajax_shoppingcart = $('#shoppingcart',html).html(); 
                    $('#shoppingcart').html(ajax_shoppingcart);
                    var ajax_basket = $('#topbanner_eshop',html).filter(":not(script)").html(); 
                    $('#topbanner_eshop').html(ajax_basket);
                  }
      开发者_如何学C      });
        }
    });

But the problem is that the data it loads into #topbanner_eshop contains some inline javascript, which breaks the page.

It tries to import the following html:

<div id="topbanner_eshop">
    <div>
        <div>
            <a href="Default.aspx?ID=24">Shop videre » </a>
        </div>
        <div>
            2 varer i kurven
        </div>
        <div>
            Total
        </div>
        <div>
            <script type="text/javascript"> 
            // var str="190,00"; 
            var str="DKK 190,00"; 
            document.write(str.replace(/,00/, ",-")); 
            </script>
        </div>
    </div>
</div>

But when it reaches the inline script it replaces the whole page with the script result.

What did i do wrong?


Well, for one thing, there's this:

 $(html).remove('script');

You're explicitly removing the script elements.

Then, the actual script uses "document.write()", which, once the containing page has been loaded, will implicitly destroy it. In other words, calling "document.write()" implicitly calls "document.open()", which, in turn, erases the DOM.

Instead of "document.write()", you could do this:

<span id='amount'></span>
<script>
  var str = "DKK 190,00"; // I presume that's actually a server-side thing
  $('#amount').text(str.replace(/,00/, ',-'));
</script>

It would be a lot better to just fix the string with server-side code.


jQuery is functioning properly. The problem is with the HTML code. Calling document.write on any page will replace the entire contents of the page with the result, so you probably want to use something else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜