2017-04-24 1 views
0

IWas ist transformRequest in AngularJS

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

Ich weiß, dass dieser Code einen Code haben, ist die Serialisierung Algorithmus ändern und die Daten mit dem Inhaltstyp veröffentlichen, "application/x-www-form-urlencoded". Aber ich weiß nicht, was Syntax davon ist. Was ist obj in Funktion. Bitte erläutern Sie für mich. Danke

+0

warum nicht einfach auf obj schweben und sehen, was es ist? oder loggen Sie es an der Konsole ein? – Haris

+0

Ich weiß nicht, wie das geht. Ich benutze Ajax, um es zu senden, wie kann ich das tun? –

+0

versuchen Sie 'console.log (obj)' – OutOfMind

Antwort

0

Transform Request wird in der Regel für die Konvertierung von Anfragedaten in einem Format verwendet, das leicht vom Server verarbeitet werden kann (Ihr Backend-Code).

Zum Beispiel - Wenn Sie Daten mit einigen Änderungen in der Anfrage senden möchten, dann können Sie es verwenden.

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

};

Verwandte Themen