[英]Regarding post requests
说我有代码:
var testVar = 0;
var newVar = "";
function(){
var info = "hello";
$.post("test.php", {"info":info}, function(data){
if(data == "success"){
testVar = 1;
}
else{
testVar = 0;
}
});
$.post("new.php", {"testVar":testVar}, function(data2){
if(data2 == "success"){
newVar = "Complete";
}
else{
newVar = "Failed";
}
});
}
假设 test.php 返回“success”并且 new.php 需要 aa 1 才能让 testVar 返回成功,我如何获得 newVar 的“Complete”? 我猜第二个 post 请求会在第一个返回数据之前发生。
你可以做:
var testVar = 0;
var newVar = "";
var secondFunction = function(){
$.post("new.php", {"testVar":testVar}, function(data2){
if(data2 == "success"){
newVar = "Complete";
}
else{
newVar = "Failed";
}
});
};
function(){
var info = "hello";
$.post("test.php", {"info":info}, function(data){
if(data == "success"){
testVar = 1;
}
else{
testVar = 0;
}
secondFunction();
});
}
如果第二个请求的参数取决于第一个请求的结果,
然后确保按顺序发送请求,
意思是只有在您收到第一个post
的回复后才发送第二个post
。
此外,您应该准备好您的响应,以包含成功标志和有效负载标志。
操作成功
{success : "true", message : "operation successful", value : "1"}
手术失败
{success : "false", message : "operation failed", value : "0"}
考虑下面的例子
function(){
var info = "hello";
$.post("test.php", {"info":info}, function(data){
if (data.success != false){
$.post("new.php", {"testVar":data.value}, function(data){
if (data.success != false){
console.log(data.message) // this is the success message from the second request
// process the data from the second response,
// var = data.value ...
}
else{
console.log(data.message) // handle the failed state for the second request
}
},"json");
}
else{
console.log(data.message)
}
},"json");
}
只有在第一个请求成功时才会触发第二个请求。
您的响应具有一定的一致性, value
的内容可以是单个值、数组或对象。
拥有成功的价值和消息,您可以轻松跟踪发生的事情,并在需要时调出通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.