Angularjs返回问题以响应$ http [英] Angularjs return issue in response of $http
本文介绍了Angularjs返回问题以响应$ http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我做了一个管理发送到服务器端的数据的功能.我想在 $ http
成功时返回响应.
I made a function for managing data sending to server side. I want to return response of $http
when it success.
我的控制器:(当我调用该函数时)
My controller: (When I call the function)
var myResponse = sendData(inputValueArray, url, onSuc, onErr, $http);
// Nothing happen here:
alert(myResponse);
我发送数据的功能:
function sendData(inputArray, url, onSuccess, onErr, $http) {
var serverResponse = "";
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http({
method: 'POST',
url: url,
data: {
myData: inputArray
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
if (response.res == true) {
onSuccess();
serverResponse = response;
}
else {
onErr();
}
})
.error(function(data, status, headers, config) {
onErr();
});
return serverResponse;
}
推荐答案
在返回 serverResponse
之前,您将返回 serverResponse
.相反,请尝试如下操作:
You are returning serverResponse
before it has any data from the call back. Instead, try something like this:
function sendData(inputArray, url, onSuccess, onErr, $http) {
var serverResponse = "";
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
return $http({
method: 'POST',
url: url,
data: {
myData: inputArray
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
然后您像这样使用它
sendData
.success(function(response) {
if (response.res == true) {
onSuccess();
serverResponse = response;
alert(serverResponse); // ************
}
else {
onErr();
}
})
.error(function(data, status, headers, config) {
onErr();
});
这篇关于Angularjs返回问题以响应$ http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文