【发布时间】:2012-04-17 15:00:53
【问题描述】:
背景:
- 使用 jQuery 1.7 客户端
- PHP 服务器端
- 通过 json_encode php 函数使用 json 响应
- content-type 标头正确,以下任何一种都有效: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())
}
);
在这两种情况下,总是会触发 complete 事件,而永远不会触发 error 事件。
但是,在第二个代码中触发了成功。
显然.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 data,如果可能的话,不将原始 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
而且我很确定它们都不是我的问题。
【问题讨论】:
标签: javascript jquery ajax