当我使用$ .post进行ajax调用时,我想要设置一些基本设置,所以每次我想使用$ .post时我都不需要将它放在我的代码中。 我这样做了:
$.ajaxSetup({
dataType :"json", // all requests should respond with json string by default
type : "POST", // all request should POST by default
beforeSend : function(){
this.url = basepath+"include/ajax/"+this.url; // before making the request, change url location to ajax folder
},
error : function(xhr, textStatus, errorThrown){
displayMessage("error", "Request could not be completed: <pre>"+errorThrown+"</pre>", true);
},
success : function(event){
console.log(event);
if(event.responseJSON !== undefined && event.responseJSON.status !== undefined && event.responseJSON.status === true){
if(event.responseJSON.output === undefined){
console.log("something is wrong 1");
displayMessage("error", "Property output was not found in response.");
}
else{
event.responseJSON.status = false;
console.log("something is wrong 2");
}
}
else{
console.log("something is wrong 3");
}
},
done : function(){
console.log("done");
},
always : function(){
console.log("always");
}
});
我像这样制作我的$ .post:
$("div#brandsView button.compose").click(function(e){
$.post("brands.php",{method:"composeMessage",data:{brand:brandId}},function(data){
console.log(data)
})
});
现在我遇到了一个问题: 我想在$ .ajaxSetup中更改“brands.php”的响应,然后再转到$ .post。正如您所看到的,我尝试过成功和完成的功能,但这些不会改变$ .post中的结果。 有谁知道这是否可能,如果有的话,该如何做?
祝你好运, 克里斯
答案 0 :(得分:0)
$.post
中的成功处理程序会覆盖$.ajaxSetup
中的成功处理程序。您应该从ajaxSetup
:
function handleSuccess(event){
console.log(event);
if(event.responseJSON !== undefined && event.responseJSON.status !== undefined && event.responseJSON.status === true){
if(event.responseJSON.output === undefined){
console.log("something is wrong 1");
displayMessage("error", "Property output was not found in response.");
}
else{
event.responseJSON.status = false;
console.log("something is wrong 2");
}
}
else{
console.log("something is wrong 3");
}
}
然后让你的$.ajaxSetup
像这样:
$.ajaxSetup({
dataType :"json", // all requests should respond with json string by default
type : "POST", // all request should POST by default
beforeSend : function(){
this.url = basepath+"include/ajax/"+this.url; // before making the request, change url location to ajax folder
},
error : function(xhr, textStatus, errorThrown){
displayMessage("error", "Request could not be completed: <pre>"+errorThrown+"</pre>", true);
},
success : handleSuccess,
done : function(){
console.log("done");
},
always : function(){
console.log("always");
}
});
然后让你的$.post
像这样:
$.post("brands.php",{method:"composeMessage",data:{brand:brandId}},function(data){
handleSuccess(data);
console.log(data);
})