开发者

prevent script execution on load (or parsing) in jQuery

开发者 https://www.devze.com 2023-03-31 14:22 出处:网络
i have an \"ajax engine\" based on jQuery. And after receiving the response i must manipulate the response before 开发者_StackOverflowinserting in page. But I need the response as an jQuery object.

i have an "ajax engine" based on jQuery. And after receiving the response i must manipulate the response before 开发者_StackOverflowinserting in page. But I need the response as an jQuery object. I do this with:

tmpActualResult = $( '<span/>' ).html( actualResult );

But at this time jQuery (or browser itself?) execute the scripts which are included in response - and exactly this shouldn't occur. I will execute the scripts manual later.

in particular I will:

  1. parse response (get access to the tags/elements which are included)
  2. insert the elements into page (DOM manipulating)
  3. execute possible scripts (which are received)

in thanks

Edit: If someone is interested too, i've created a more general solution by extending the jQuery.domManip function, as suggested in first answer.

(function($, oldDomManip) {
// Override the core domManip function
$.fn.domManip = function() {

    function evalScript(i, elem) {
        jQuery.globalEval(elem.text || elem.textContent || elem.innerHTML || "");
    }

    var scripts = [];
    // let jQuery build the fragments
    var results = jQuery.buildFragment(arguments[0], this, scripts);
    // change parameter to created fragments
    arguments[0] = results.fragment.childNodes;
    // do what jQuery will do - without scripts
    oldDomManip.apply(this, arguments);
    if (scripts.length) {
        // if connection is active
        if (jQuery.active != 0) {
            $(this).bind("ajaxStop.scriptCache", function() {
                $.each(scripts, evalScript);
                $(this).unbind("ajaxStop.scriptCache");
            });
        } else
            $.each(scripts, evalScript);
    }
    return this;
};
})(jQuery, jQuery.fn.domManip);

it will not execute scripts before ajax request is completed. worked for me.


You can't prevent script execution of scripts that are part of a string of markup you're trying to add using .html() or .append(). At least not without extending the domManip function of jQuery. It extracts all scripts in html markup that you're trying to add using .html() or .append() and evals it.

You could, however, extract the script tags with their inner text (js) from the string yourself, add only the markup via .html() or .append() and then eval the scripts yourself when you need to.


Try this:

var container = document.createElement('div');
container.innerHTML = "<div> i am html with script tag <script type="text/javascript">alert('Script executed');</script>end</div>"
$(container).doSomething()
0

精彩评论

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

关注公众号