Home > Article > Web Front-end > Example of passing json parameters through $http service Post method under AngularJS
Below I will share with you an example of passing json parameters through the $http service Post method under AngularJS. It has a good reference value and I hope it will be helpful to everyone.
This article mainly introduces how to use the Angularjs $http service to transfer json object data to the server using the POST method.
The details are as follows:
1. The default data type submitted by the $http POST method is application/json
var data = {'wid':'0', 'praise' : '25'}; $http.post(url, data).success(function(result) { // });
The final request sent is:
POST http://www.example.com HTTP/1.1 Content-Type: application/json;charset=utf-8 {'wid':'0','praise':'25'}
The default method can directly pass the json object to the server in the form of a string, which is more suitable for RESTful interfaces. But the $_POST of the php script cannot get the json data from the request body.
You can use this:
$data = file_get_contents("php://input"); //获得原始输入流
Note: php://input is invalid when enctype="multipart/form-data"
After obtaining the original input stream of the request and then processing it accordingly, you can get the json data.
2. Submit the json data using x-www-form-urlencoded method
app.factory("Comment",function($http){ return { get : function(commentFileUrl) { return $http({ method: "GET", url: commentFileUrl, params: {R:Math.random()}, headers: {'Cache-Control':'no-cache'} }); }, //保存一个评论 save : function(toUrl,saveFileUrl,Data) { $http({ method: "POST", url: toUrl, data: {saveUrl:saveFileUrl,commit:Data}, headers: { 'Content-Type': '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("&"); } }).success(function(data){ console.log("数据已保存!"); }).error(function(data) { alert("数据保存失败,错误信息:" + JSON.stringify({data:data})); }); } } }); var updateClickRate={'wid':'0','click_rate':'87'}; Comment.save("php/updateWork.php","../userdata/work_content.json",JSON.stringify(updateClickRate));
Finally sent request It’s:
The above is what I compiled for you. I hope it will be helpful to you in the future.
Related articles:
A brief introduction to the Node debugging tool tutorial
Examples of webpack packaging and compression methods for js and css
Sample code for dynamically loading and removing js/css files
The above is the detailed content of Example of passing json parameters through $http service Post method under AngularJS. For more information, please follow other related articles on the PHP Chinese website!