我有一个AngularJS 1.5应用程序,其中包含一个将数据发布到数据库的表单。在表单中有一个下拉选择。问题是,下拉POST中的一些选项成功,而其他选项遇到POST错误说
POST http://localhost/myURL 500 (Internal Server Error)
在它下面......
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.qc [as fromJson] (angular.js:1285)
at apiError (postFormCtrl.js:957)
at AjaxServices.js:37
at angular.js:11029
at angular.js:15616
at m.$eval (angular.js:16884)
at m.$digest (angular.js:16700)
at m.$apply (angular.js:16992)
at g (angular.js:11313)
什么可能导致同一表单中的某些项成功POST,其他人遇到此错误?我已经仔细检查了缺少逗号,括号等的代码......没有。
我已经检查了浏览器的输出,成功帖子的响应标题有
POST失败时,响应头中的Content-Type:application/json
Content-Type:text/html
在响应标题中。这可能是问题吗?
如果是,我该如何阻止它,因为我没有在应用程序中设置内容类型为text / html的单个设置。
另外,我知道问题不能在ajax post函数中,因为整个应用程序使用相同的ajax post函数并且它们运行良好。
更多信息
这是下拉选择中项目的示例:
<div class="row" ng-if="isStudentActivity">
<div class="col-sm-10">
<label for="activity">Select an activity:</label>
<div>
<ui-select ng-model="theactivity.selected" theme="select2" class="form-control" name="activity" required>
<ui-select-match placeholder="Select or search an activity...">
<span>{{$select.selected.activity}}</span>
</ui-select-match>
<ui-select-choices repeat="item in activities | filter: $select.search">
<span ng-bind-html="item.activity | highlight: $select.search"></span>
</ui-select-choices>
</ui-select>
<p ng-show="dataFilterForm.activity.$invalid && (!dataFilterForm.activity.$pristine || dataFilterForm.$submitted)" class="help-block"><i class="fa fa-exclamation-triangle"></i> You must choose an activity.</p>
</div>
</div>
</div>
这是应用程序中所有POST使用的ajax函数
this.AjaxPost2 = function (data, route, successFunction, errorFunction, extras)
{
$http({
method: 'POST',
url: route,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
}).success(function (response, status, headers, config) {
successFunction(response, status, extras);
}).error(function (response) {
errorFunction(response);
});
}
并且使用该函数调用
this.addCommunication = function (request, successFunction, errorFunction, params) {
ajaxService.AjaxPost2(request, path + "/addCommunication", successFunction, errorFunction, params);
};
我猜错误html不是由您的代码生成的,而是由主机(如IIS)生成的。使用json数据创建错误响应可能是更好的做法。无论如何,你可以在angularJs中单独处理ok和错误响应。
$http.post
返回一个promise对象,可以像
$http.post(url, data)
.then(function(response){
//handle normal result data here
})
.catch(function(response){
//handle error case here
})
它没有完全完成的问题。您必须提及您尝试解析的数据及其响应。
您收到500错误,似乎您从服务器收到错误。这意味着你的后端代码制作错误。
另请检查您的解析dataType。
我想你必须提到responseType
到"json"
。
this.AjaxPost2 = function (data, route, successFunction, errorFunction, extras)
{
$http({
method: 'POST',
url: route,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data,
responseType: 'json',
}).success(function (response, status, headers, config) {
successFunction(response, status, extras);
}).error(function (response) {
errorFunction(response);
});
}
您必须提到要解析的数据。