[英]Angularjs $http not sending form data to the server
The below code works if I use jquery ajax but $http
of Angular doesn't send any data to the server using the code below: 如果我使用jquery ajax但以下代码有效,但Angular的
$http
不会使用以下代码向服务器发送任何数据:
myapp.factory('startCampFactory',function($http,$q,$rootScope){
return {
startNewCampaign : function(){
var e = $("input#email");
var email = e.val();
var campname = $("input#campaignname").val();
var about = $("textarea#about").val();
var tamt = $("input#targetamount").val();
var edate = $("input#enddate").val();
var invitees = $("input#invitees").val();
var file_data = $("#file").prop("files")[0];
var form_data = new FormData();
form_data.append("file",file_data);
form_data.append("email",email);
form_data.append("campaignname",campname);
form_data.append("about",about);
form_data.append("targetamount",tamt);
form_data.append("enddate",edate);
form_data.append("invitees",invitees);
console.log(email+about+campname);
var deferred = $q.defer();
$http({
method:'POST',
url:'/startcampaign',
data:form_data,
headers:
{
'Content-Type' :'application/x-www-form-urlencoded'
}
}).success(function(data,status,headers,config) {
$rootScope.$apply( function() {
deferred.resolve();
});
}).error(function(){
$rootScope.$apply(function()
{
deferred.reject();
});
});
return deferred.promise;
}
});
Try something like this : 尝试这样的事情:
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
Refer this link for explanation : 请参阅此链接以获取解释:
http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
I had no luck with this either, and ending up using jQuery.ajax (although I was using jsonp). 我也没有运气,最后使用jQuery.ajax(尽管我使用的是jsonp)。
See How can I post data as form data instead of a request payload? 请参阅如何将数据作为表单数据而不是请求有效负载发布?
Perhaps "And the data passed should be converted to a string" is relevant. 也许“并且传递的数据应该转换为字符串”是相关的。
data
in jQuery's $.ajax
does not correspond to data
in Angular's $http.get/post
. data
在jQuery的$.ajax
没有对应data
在角的$http.get/post
。 You may have to use params
instead of data
in Angular. 您可能必须使用
params
而不是Angular中的data
。 Have you looked at this: 你看过这个:
jQuery ajax request works, same AngularJS ajax request doesn't jQuery ajax请求有效,同样的AngularJS ajax请求没有
the problem is occurring due to content type, remove the headers part or add 问题是由于内容类型,删除标题部分或添加
contentType:false or 'multipart/form-data'
$http({
method:'POST',
url:'url'
data:formData,
contentType:false,
processData: false
}).
then(function(result) {
alert(result);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.