【问题标题】:What is transformRequest in angularjs什么是angularjs中的transformRequest
【发布时间】:2019-01-14 15:46:47
【问题描述】:

我有密码

 transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    }

我知道这段代码是更改序列化算法并使用内容类型“application/x-www-form-urlencoded”发布数据。但我不知道它的语法是什么。函数中的obj 是什么。请为我解释。谢谢

【问题讨论】:

  • 为什么不直接将鼠标悬停在 obj 上,看看它是什么?或将其记录到控制台?
  • 我不知道该怎么做。我用ajax发送,怎么办?
  • 试试console.log(obj)

标签: angularjs


【解决方案1】:

Transform Request 通常用于将请求数据转换为服务器可以轻松处理的格式(您的后端代码)。

例如 - 如果您想在请求中进行一些修改后发送数据,那么您可以使用它。

       $scope.save = function() {
    $http({
        method: 'POST',
        url: "/Api/PostStuff",
        //IMPORTANT!!! You might think this should be set to 'multipart/form-data' 
        // but this is not true because when we are sending up files the request 
        // needs to include a 'boundary' parameter which identifies the boundary 
        // name between parts in this multi-part request and setting the Content-type 
        // manually will not set this boundary parameter. For whatever reason, 
        // setting the Content-type to 'undefined' will force the request to automatically
        // populate the headers properly including the boundary parameter.
        headers: { 'Content-Type': undefined},
        //This method will allow us to change how the data is sent up to the server
        // for which we'll need to encapsulate the model data in 'FormData'
        transformRequest: function (data) {
            var formData = new FormData();
            //need to convert our json object to a string version of json otherwise
            // the browser will do a 'toString()' on the object which will result 
            // in the value '[Object object]' on the server.
            formData.append("model", angular.toJson(data.model));
            //now add all of the assigned files
            for (var i = 0; i < data.files; i++) {
                //add each file to the form data and iteratively name them
                formData.append("file" + i, data.files[i]);
            }
            return formData;
        },
        //Create an object that contains the model and files which will be transformed
        // in the above transformRequest method
        data: { model: $scope.model, files: $scope.files }
    }).
    success(function (data, status, headers, config) {
        alert("success!");
    }).
    error(function (data, status, headers, config) {
        alert("failed!");
    });
};

};

【讨论】:

  • transformRequest: function (data)请告诉我data参数的值是从哪里来的?
  • habib,大概来自属性:data: { model: $scope.model, files: $scope.files }
猜你喜欢
  • 2014-08-01
  • 2016-08-11
  • 1970-01-01
  • 2014-01-19
  • 2016-02-04
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
相关资源
最近更新 更多