Angularjs Angular.js中的$http post
我刚刚开始学习Angular.js。如何在Angular.js中重新编写以下代码Angularjs Angular.js中的$http post,angularjs,angular-http,Angularjs,Angular Http,我刚刚开始学习Angular.js。如何在Angular.js中重新编写以下代码 var postData = "<RequestInfo> " + "<Event>GetPersons</Event> " + "</RequestInfo>"; var req = new XMLHttpRequest(); req.onreadystatechange = functi
var postData = "<RequestInfo> "
+ "<Event>GetPersons</Event> "
+ "</RequestInfo>";
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 || req.readyState == "complete") {
if (req.status == 200) {
console.log(req.responseText);
}
}
};
try {
req.open('POST', 'http://samedomain.com/GetPersons', false);
req.send(postData);
}
catch (e) {
console.log(e);
}
html
{{person.name}
如果您将
$scope.persons
分配给$http
,这是一个承诺对象,因为$http
返回一个承诺对象,那么我的方向正确吗?在您当前的函数中
因此,与其将scope.persons
分配给$http,不如将$scope.persons
分配给$http
中的success,如下所述:
function TestController($scope, $http) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.persons = data; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
这里是由Ajay beni给出的解决方案的一个变体。使用then方法可以链接多个承诺,因为then返回一个新承诺
function TestController($scope) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
}
);
}
使用$http:
实施示例:
$http.post('http://service.provider.com/api/endpoint', {
Description: 'Test Object',
TestType: 'PostTest'
}, {
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
).then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});
我们来分析一下:Url有点明显,所以我们跳过它
{
Description: 'Test Object',
TestType: 'PostTest'
}
{
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
谢谢,我尝试了很多解决方案,但是标题:
{'Content-Type':'application/x-www-form-urlencoded'}
请注意,success
和error
函数现在已经弃用。请参阅
$http.post('http://service.provider.com/api/endpoint', {
Description: 'Test Object',
TestType: 'PostTest'
}, {
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
).then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});
{
Description: 'Test Object',
TestType: 'PostTest'
}
{
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
.then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});