404错误的请求,同时发布json对象到服务器
问题描述:
我想通过ajax调用将json对象传递给服务器。但它是抛出404错误请求。其实我有一个表单,我将这个表单数据转换为json对象。在表中,我已经设置了ID作为自动递增的主键,并且我的表单没有字段ID。 这是我的控制器404错误的请求,同时发布json对象到服务器
var Bus= angular.module('Bus',[]);
Bus.controller('BusController',function($scope,$http) {
$scope.business = {}
$scope.submitMyForm=function(){
console.log($scope.business);
var q=JSON.stringify($scope.business)
console.log(q)
$
.ajax({
type : 'POST',
url : " some url",
data :JSON.stringify($scope.business),
success: function(){
alert('success');
},
error : function(e) {
console.log(e);
alert('oops!!');
},
dataType : "json",
contentType : "application/json"
});
};
});
如何解决这个问题? 在此先感谢!
答
404 Not Found or 400 Bad Request?
如果它实际上是抛出404您的URL是错误的。如果它是400:
您是否使用调试器检查过$scope.business
对象是否实际上包含所有正确的值?
在一个侧面说明:您不应该在一个角控制器使这些请求,但使用服务,而不是:
Bus.service('MyService', function($http) {
function postForm(form) {
var data = angular.toJSON(form);
// proceed with the $http stuff ...
}
return {
postForm: postForm
};
});
而在你的控制器注入的服务,并调用它像这样:
Bus.controller('BusController',function($scope, MyService) {
$scope.submitMyForm = function() {
MyService.postForm($scope.business);
};
});
以任何方式了解您的后端所期望的JSON格式以及由您的客户端产生的JSON以了解发生了什么问题会很有帮助。