我想在通过Ext.Ajax.request加载的页面中执行javascript.为此,我必须像这样加载脚本并eval():
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]);
}
}
});
但是,使用JQuery,我可以在通过AJAX调用的页面中执行Java脚本,而无需借助eval()这样的代码:
function replaceContentOnClick(id, pagetoLoad) {
$('body').delegate(('#' + id), 'click', function(){
$.get('content/' + pagetoLoad, function(data) {
$('#regionContent .x-panel-body').html(data);
});
});
}
JQuery如何在不使用eval()的情况下设法执行已加载页面中的javascript?有没有一种方法可以在不使用ExtJS中的eval()的情况下加载javascript?
解决方法:
就个人而言,我不会担心评估声明.我知道Douglas Crockford建议不要使用它:
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.
(从http://www.jslint.com/lint.html起)
他在这里指出“有时这是必要的”,我认为您的使用是有效的.
JSON2.js库(http://www.json.org)使用此命令,并向JSLint标记这是预期的:
/*jslint evil: true */
您是否有特定的原因想要避免使用它?