本文主要介紹如何使用Angularjs $http服務(wù)以POST方法向服務(wù)器傳遞json對(duì)象數(shù)據(jù)。
具體如下:
一、$http POST方法默認(rèn)提交數(shù)據(jù)的類型為application/json
var data = {'wid':'0', 'praise' : '25'}; $http.post(url, data).success(function(result) { // });
最終發(fā)送的請(qǐng)求是:
POST http://www.example.com HTTP/1.1 Content-Type: application/json;charset=utf-8 {'wid':'0','praise':'25'}
默認(rèn)的這種方式可以直接將json對(duì)象以字符串的形式傳遞到服務(wù)器中,比較適合 RESTful 的接口。但是php腳本的$_POST無(wú)法從請(qǐng)求體中獲得json數(shù)據(jù)。
此時(shí)可以用:
$data = file_get_contents("php://input"); //獲得原始輸入流
注:enctype="multipart/form-data" 的時(shí)候 php://input 是無(wú)效的
獲得請(qǐng)求原始輸入流之后再做相應(yīng)處理就可以獲得json數(shù)據(jù)了。
二、 采用x-www-form-urlencoded 方式提交獲得json數(shù)據(jù)
app.factory("Comment",function($http){ return { get : function(commentFileUrl) { return $http({ method: "GET", url: commentFileUrl, params: {R:Math.random()}, headers: {'Cache-Control':'no-cache'} }); }, //保存一個(gè)評(píng)論 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("數(shù)據(jù)已保存!"); }).error(function(data) { alert("數(shù)據(jù)保存失敗,錯(cuò)誤信息:" + JSON.stringify({data:data})); }); } } }); var updateClickRate={'wid':'0','click_rate':'87'}; Comment.save("php/updateWork.php","../userdata/work_content.json",JSON.stringify(updateClickRate));
最終發(fā)送的請(qǐng)求是:
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請(qǐng)關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
Koa2實(shí)現(xiàn)文件上傳步奏詳解
jQuery實(shí)現(xiàn)上傳圖片時(shí)預(yù)覽功能
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com