根据文件:
如果指定了html,则在将HTML作为字符串返回之前,将执行检索到的数据中的任何嵌入式JavaScript.同样,脚本将执行从服务器撤回的JavaScript,然后不返回任何内容.
怎么预防这个?我有js将修改通过ajax获得的内容.在返回html之前执行它是没有意义的,因为它没有内容可以处理(至少在我的情况下).
我的代码:
function do_ajax(url)
{
$.ajax(
{
cache: false,
url : url,
success: function(response, status, xhr)
{
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('script') > -1) {
try {
eval(response);
}
catch(error) { }
}
else
{
var edit_dialog = $('<div class="edit_dialog" style="display:hidden"></div>').appendTo('body');
edit_dialog.html(response);
edit_dialog.dialog({ modal:true, close: function(event, ui) { $(this).dialog('destroy').remove(); } });
}
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
}
Run Code Online (Sandbox Code Playgroud)
ajax收到的脚本执行两次.首先由我在eval(响应)中,然后jquery再次执行它(如文档中所述)