在AngularJs中以表单数据类型将数据发布到API
我是angularjs新手,我想以“表单数据”类型的形式发布数据,而不是查询字符串。我使用的代码是:在AngularJs中以表单数据类型将数据发布到API,angularjs,Angularjs,我是angularjs新手,我想以“表单数据”类型的形式发布数据,而不是查询字符串。我使用的代码是: angular.module('odeskApp') .factory('Password', function ($http, $q) { return { update: function (pwd) { var deferred = $q.defer(); $http({ url:
angular.module('odeskApp')
.factory('Password', function ($http, $q) {
return {
update: function (pwd) {
var deferred = $q.defer();
$http({
url: 'http://example.com/api/user/password',
method: 'POST',
data: $.param({
'password': pwd
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
}
})
.success(function (data) {
$('#changePasswordAlert').html('<div class="alert alert-success"><b>Successfully Done!</b> Change password process completed.</div>');
$('#changePasswordAlert .alert').mouseout(function(){ $(this).fadeOut('slow'); });
deferred.resolve(data); //resolve data
})
.error(function (err) {
$('#changePasswordAlert').html('<div class="alert alert-danger"><b>Failed!</b> Change password process failed.</div>');
deferred.reject();
$('#changePasswordAlert .alert').mouseout(function(){ $(this).fadeOut('slow'); });
});
return deferred.promise;
}
};
});
angular.module('odeskApp'))
.factory('Password',函数($http,$q){
返回{
更新:功能(pwd){
var deferred=$q.deferred();
$http({
网址:'http://example.com/api/user/password',
方法:“POST”,
数据:$.param({
“密码”:pwd
}),
标题:{
“内容类型”:“应用程序/x-www-form-urlencoded;字符集=UTF-8”,
“X-request-With':“XMLHttpRequest”
}
})
.成功(功能(数据){
$('#changePasswordAlert').html('成功完成!更改密码过程已完成');
$('#changePasswordAlert.alert').mouseout(函数(){$(this.fadeOut('slow');});
deferred.resolve(数据);//解析数据
})
.error(函数(err){
$('#changePasswordAlert').html('失败!更改密码过程失败');
拒绝();
$('#changePasswordAlert.alert').mouseout(函数(){$(this.fadeOut('slow');});
});
回报。承诺;
}
};
});
任何可能的帮助或建议将不胜感激
谢谢最好的通话方式是使用简单的$http.post:
$http.post(url, {'password': pwd}, configs)
.then(sucessFunc, failFunc);
我抽象了完整的示例,使其清晰明了。如果你愿意,我可以把完整的代码
编辑:完整示例
angular.module('odeskApp')
.factory('Password', function ($http) {
var url = 'http://example.com/api/user/password';
// you can remove the configs if they are not needed...
var configs = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
}
};
return {
update: function (pwd) {
$http.post(url, {'password': pwd}, configs)
.then(function (data){ return data; });
}
};
});
这应该行得通。我没有在失败时添加Refect,因为它会自动将拒绝发送到承诺队列。
还有$http返回承诺,因此无需使用$q。
Html操作不应在工厂中使用。这就是我将其从示例中删除的原因。请参阅有关角度文档的一些指南。
基本上,您应该有一个使用控制器的模板,该模板调用此服务,然后使用$scopes在控制器和视图之间传递消息。
希望这能让您顺利完成。非常感谢您的回复。我拖了很久的后腿。我试过类似的代码,但没能成功。如果可能,请张贴完整的代码。签出这篇文章