2017-04-24 29 views
0

我有一個代碼什麼是transformRequest在angularjs

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

我知道這個代碼是改變序列化算法,並與內容類型,「應用程序/ x-WWW的形式,進行了urlencoded」發佈的數據。但我不知道它的語法是什麼。功能中obj是什麼。請爲我解釋。感謝

+0

爲什麼你只是停留在obj上,看看它是什麼?或者將其記錄到控制檯? – Haris

+0

我不知道該怎麼做。我使用ajax發送它,我該怎麼做? –

+0

嘗試'console.log(obj)' – OutOfMind

回答

0

轉換請求通常用於轉換服務器可以輕鬆處理的格式(您的後端代碼)的請求數據。

例如 - 如果您希望發送數據並在請求中進行一些修改,那麼您可以使用它。

 $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 'false' will force the request to automatically 
     // populate the headers properly including the boundary parameter. 
     headers: { 'Content-Type': false }, 
     //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!"); 
    }); 
}; 

};