【问题标题】:404 Bad Request while posting json object to server将 json 对象发布到服务器时出现 404 错误请求
【发布时间】:2017-03-07 18:08:41
【问题描述】:

我正在尝试通过 ajax 调用将 json 对象传递给服务器。但它抛出 404 Bad Request。实际上我有一个表单,我正在将此表单数据转换为 json 对象。在表中,我将 id 设置为自动递增的主键,并且我的表单没有字段 id。 这是我的控制器

     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"
            });
        };
}); 

如何解决问题? 提前致谢!!

【问题讨论】:

    标签: javascript java angularjs ajax controller


    【解决方案1】:

    404 未找到或 400 错误请求?

    如果它实际上是抛出 ​​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 有助于了解问题所在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 2016-10-19
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      相关资源
      最近更新 更多