本文介绍了什么是angularjs中的transformRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个密码

 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是什么.请给我解释一下.谢谢

I know this code is change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded". But i dont know what is syntax of it . What is obj in function . Please explain for me . Thank

推荐答案

转换请求通常用于转换请求数据,其格式可以由服务器轻松处理(您的后端代码).

Transform Request is generally used for converting request data in the format which can be easily handled by server (Your Back end code).

例如-如果您要发送请求中的某些修改的数据,则可以使用它.

For Example - If you want to send data with some modification in request then you can use it .

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

};

这篇关于什么是angularjs中的transformRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:30