How to prevent jquery from removing the [removed] tags

前端 未结 2 742
你的背包
你的背包 2020-12-18 07:09

How do I prevent the default behaviour of jquery stripping out my JS?

function callBackFunctionLoadPage(data)
{
    var data = $(data).find(\'#content\');
           


        
相关标签:
2条回答
  • 2020-12-18 07:47

    I suggest you do things differently. Firstly, ajax calls are good because they're lightweight, so instead of loading a whole page, you can just grab the updated data and inject it where necessary. If you're getting a giant set of markup including scripts you're essentially using ajax to do a normal http page request. That's like looking at the fast line in the supermarket (10 items or less) and seeing it move faster than the isle you're currently standing in, so you move there. But if you do that for every request, you end up turning the fast lane into a normal lane.

    Getting javascript code from the server to execute is usually a sign that you're not thinking correctly about the problem, since your mixing domains horribly.

    Firstly, why not just have a function that executes every time you ajax the next page/gallery in? Why do you need to get the code from the server? In accordance with my first point, why not just get an array of new filenames and build the new gallery from those?

    If for some reason you feel you want to continue this way anyway (I should point out at this point that executing code in such a manner is not just bad practise but unsafe in certain circumstances), you can extract the code and eval it:

    Assuming there's only one block of code, and it's wrapped in <script></script> (which is not taking into account all sorts of whitespace and funny characters):

    function callBackFunctionLoadPage(data)
    {
        ...
        eval(data.match(/<script>(.*)<\/script>/im)[1]);
    }
    

    UPDATE

    jquery strips out the javascript but it still executes it:

    $('#content').html('<div><script>alert("hello, world!");</script></div>');
    

    So there is almost no reason to want the script tags themselves if their content is already executed...

    UPDATE 2 (for non-believers)

    var scriptDiv = $('<div><span></span><script>alert("boom!");</script></div>');
    alert("not yet"); // the above is created but not executed until added to the DOM
    $('body').append(scriptDiv); // there you go, proof that it is executed
    alert(scriptDiv.html()); // to prove that the script was stripped
    
    0 讨论(0)
  • 2020-12-18 07:57

    Have you tried using JS's native innerHTML ?

    $("#content").get(0).innerHTML = data;
    

    If this works, as davin pointed out, you still have to evaluate the scripts:

    eval(data.match(/<script>(.*)<\/script>/im)[1]);
    

    Loading and evaluating SCRIPT form AJAX should work in general.

    0 讨论(0)
提交回复
热议问题