如何使用Angular.js的$http发送同步请求
How to send Synchronous Requests with $http of Angular.js
嘿,伙计们,我知道这个问题发布了很多,但没有什么对我没有帮助,这就是我问这个问题的原因。问题是我面临着向php发送同步请求的问题。这是我的Model函数,它正在发送请求。
State.pushData = function () {
$http({
method: 'POST',
url: 'pushData.php?action=pushdata',
data: {'status': 'push', 'email' : State.campemail},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response){
if(response.error){
console.log(response.error);
return;
}
State.getCartData();
State.selectedItems = [],
});
}
这个pushData函数向定义的url发送一个post请求。并获取响应。编写的代码假设在最初发送的请求成功时执行"State.getCartData()"函数。但这并没有以这种方式起作用。两个请求同时执行。我曾尝试过$http与.post和then方法,但结果相同。像这个
State.pushData = function () {
$http.post('pushData.php?action=pushdata',
{'status': 'push', 'email' : State.campemail}
).then(function(response){
if(response.error){
console.log(response.error);
return;
}
State.getCartData();
State.selectedItems = [],
});
}
我想异步发送请求,一旦pushQuote请求完成,getCartData()函数就会执行。请分享你的经验。提前谢谢。
经过集思广益,得到了我的问题的答案。我在模型中返回$http,并在返回的响应中调用.then()。它的工作原理是,一旦第一个成功完成,我想发送请求。这是我的模型函数
State.pushData = function () {
return $http.post('pushData.php?action=pushdata',
{'status': 'push', 'email' : State.campemail}
);
}
在上面的函数中,我只是将post请求发送到服务器,并将其响应返回到控制器函数。它在从模型返回之后立即执行。这是我的控制器功能。
scope.pushIt = function() {
var responseObj = State.pushData();
responseObj.then(
function() { //successs call back
/*Business logic*/
State.getCartData();
State.selectedItems = []
},
function() { //Error call back
/*Business logic*/
}
);
}
这种方法的美妙之处在于,你可以随心所欲地使用这种方法。它们都将在链中一个接一个地执行。
scope.pushIt = function() {
var responseObj = State.pushData();
responseObj.then(
function() { //successs call back
/*Business logic*/
},
function() { //Error call back
/*Business logic*/
}
).then(
function() { //successs call back
/*Business logic*/
},
function() { //Error call back
/*Business logic*/
}
);
}
相关文章:
- 根据最新响应在 Node 中发送同步请求
- 同步请求谷歌地图地理编码
- 火狐插件 SDK 同步请求
- 以发送的相同顺序显示 AJAX 响应,而不使用同步请求
- jquery 1.4,同步请求
- 如何为JQuery$.ajax同步请求设置超时并执行某些操作
- 节点4.2.0 phantom stdout:NETWORK_ERR:XMLHttpRequest异常101:同步请求中
- 正在包装主干同步请求
- RequireJS:同步请求文本内容
- mongodb同步请求
- Marketo-Munchkin同步请求损害了JS的性能
- 节点.js中的同步请求
- 循环中与 ajax 的同步请求
- 用于缓存的Node.js同步请求
- js 1.10, jquery 2.1和同步请求
- AJAX同步请求和操作,同时等待
- 我如何在主干运行一个基本的GET /同步请求
- 为什么异步xmlhttprequest优于同步请求?
- 使用JavaScript同步请求图像
- HTTP同步请求阻止我的GIF在Chrome和IE中移动