背景:
- 使用 jQuery 1.7 客户端
- PHP 服务器端
- 通过 json_encode PHP 函数使用 json 响应
- 内容类型 header 正确,以下任意一项均有效:text/plain、text/x-json、application/json。
- 我的 php 代码没有抛出任何错误
- 正在开发 Firefox 11
- 正在使用 js 控制台和其他 Web 的开发者工具
- HTTP/1.1 200 正常
在此 Javascript 代码中,success
事件永远不会被触发:
$.ajaxSetup({cache:false,
success:function(d) {
console.log("ok from setup with data "+d.toSource())
},
complete:function(xhr,ts){
console.log("Ajax finished reponse:"+xhr.responseText)
},
error:function(jqXHR, textStatus, errorThrown){
console.log("Error")
}
});
$.getJSON("test2.php",{},function(data){
//some code here
});
当我这样做时,它有效:
$.ajaxSetup({cache:false,
complete:function(xhr,ts){
console.log("Ajax completado con:"+xhr.responseText)
},
error:function(jqXHR, textStatus, errorThrown){
console.log("Error")
}
});
$.getJSON("test2.php",{},
function(data){
//some code here
}).success(function(d){
console.log("success applied directly, data "+d.toSource())
}
);
在这两种情况下,总是会触发完整事件,而永远不会触发错误事件。
但是,在第二个代码中,成功被触发。
显然是.get()
方法是一样的。
PHP 代码:
<?php header("Content-Type:application/json;charset=utf-8");
//or whatever text/x-json text/plain, even text/html, jquery do the dirty job
echo json_encode(array("stat"=>"1")) ?>
我的目标:
- 我想对所有 ajax 请求触发相同的成功事件
- 我想在成功事件中使用请求返回的 json数据,如果可能的话,无需再次将原始 jqXHR responseText 转换为 json里>
问题很奇怪,有什么想法吗?
我阅读了所有这些问题:
- Ajax success event not working
- AjaxSetup never execute the success function
- Does jQuery ajaxSetup method not work with $.get or $.post?
- $.ajax function's success: not firing
而且我很确定它们都不是我的问题。
最佳答案
查看 ajaxSetup 文档:http://api.jquery.com/jQuery.ajaxSetup/
Note: Global callback functions should be set with their respective global Ajax event handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than within the options object for $.ajaxSetup().
我认为这就是你的问题。
更新
如果您希望您的 ajax 处理程序对于页面上的任何 ajax 请求都是全局的,请执行以下操作:
$(document).ajaxSuccess(function(d){
console.log("ok from setup with data "+d.toSource());
});
关于javascript - jQuery ajax 成功事件奇怪地不适用于 ajaxSetup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10002048/