我有一个代码
line9) 9999999999
line8) 8888888888
line7) 7777777777
line6) 6666666666
line5) 5555566666
line4) 4444444444
line3) 3333333333
line2) 2222222222
line1) 1111111111
line6) 6666666666
line5) 5555566666
line4) 4444444444
line3) 3333333333
line2) 2222222222
line1) 1111111111
我知道这段代码更改了序列化算法,并使用内容类型“application / x-www-form-urlencoded”发布数据。但我不知道它的语法是什么。功能中 transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
是什么。请解释一下。感谢
答案 0 :(得分:2)
转换请求通常用于以服务器(您的后端代码)可以轻松处理的格式转换请求数据。
例如 - 如果您想在请求中发送一些修改数据,那么您可以使用它。
$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!");
});
};
};