简体   繁体   中英

How can I execute Javascript via ExtJS AJAX call without eval() as I can with JQuery?

I would like to execute javascript in pages which I load via Ext.Ajax.request . To do this, I have to load the scripts and eval() them like this:

Ext.Ajax.request({
    url: 'content/view_application.php',
    success: function(objServerResponse) {
        var responseText = objServerResponse.responseText;
        regionContent.update(responseText);
        var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
        while(scripts=scriptsFinder.exec(responseText)) {
            eval(scripts[1]);
        }
    }
});

With JQuery, however, I can have Javascript executed in pages which are called via AJAX without resorting to eval() like this:

function replaceContentOnClick(id, pageToLoad) {
    $('body').delegate(('#' + id), 'click', function(){
        $.get('content/' + pageToLoad, function(data) {
            $('#regionContent .x-panel-body').html(data);
        });
    });
}

How is it that JQuery manages to execute the javascript in the loaded page without eval() ? Is there a way to load the javascript without resorting to eval() in ExtJS as well?

Personally, I wouldn't worry about the eval statement. I am aware that Douglas Crockford counsels against its use:

eval is evil

The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.

(from http://www.jslint.com/lint.html )

Here he states that "This is sometimes necessary", and I would argue that your use is a valid one.

The JSON2.js library ( http://www.json.org ) uses this command, and flags to JSLint that this is intended:

/*jslint evil: true */

Is there a particular reason that you would like to avoid its use?

Well, go to the jQuery source (http://code.jquery.com/jquery-latest.js) and Ctrl+F for globalEval: function . This is the function which runs JavaScript. You'll see it actually adds script tags into the DOM. As for extJS, I don't know. Try searching in their source code for "script" or 'script' to see if they insert script tags anywhere in a similar way. Or you could just implement your own globalEval .

At the risk of sounding like a broken record , please see my other answer regarding the loadScripts config. You should consider sticking to the same question when it's just a follow-up to what you've already asked, rather than starting brand new questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM