快速解決angularJS中用post方法時后臺拿不到值的問題
用angularJS中的$http服務(wù)碰到了一個問題:運(yùn)用$http.post方法向后臺傳遞數(shù)據(jù)時,后臺的php頁面獲取不到data參數(shù)傳過來的值。
不論是這種姿勢:
$http.post( "1.php", { id: 1 }).success(function (data) { console.log(data); });
還是這種姿勢:
$http({ method: 'POST', url: '1.php', data: { id: 1 } }).success(function (data) { console.log(data); });
后臺php中的$_POST或$_REQUEST都無法獲取到data中的值:
<?php echo json_encode($_POST); ?>
輸出為一個空數(shù)組。為了測試php本身是不是真的獲取不到值,我就寫了個表單測試下:
<form action="1.php" method="post"> <input type="text" name="tid"> <input type="submit" value="submit"> </form>
輸出結(jié)果為:{"tid":"2"},也就是說表單里的值是可以獲取的,但是用ajax發(fā)送的數(shù)據(jù)獲取不了!
那么表單數(shù)據(jù)和ajax發(fā)送的post數(shù)據(jù)之間有什么差異呢?于是我悄悄瞄一眼請求頭...
1.表單的請求頭部:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.8,ja;q=0.6 Cache-Control: no-cache Connection: keep-alive Content-Length: 5 Content-Type: application/x-www-form-urlencoded Cookie: a0537_times=1 Host: 127.0.0.1 Origin: http://127.0.0.1 Pragma: no-cache Referer: http://127.0.0.1/angularTest/1.html Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
2.ajax發(fā)送的數(shù)據(jù)的請求頭部:
Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.8,ja;q=0.6 Cache-Control: no-cache Connection: keep-alive Content-Length: 10 Content-Type: application/json;charset=UTF-8 Cookie: a0537_times=1 Host: 127.0.0.1 Origin: http://127.0.0.1 Pragma: no-cache Referer: http://127.0.0.1/angularTest/1.html User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
問題一下子就出來了!表單發(fā)送的文本類型是表單類型,而angular的ajax默認(rèn)發(fā)送的則是json數(shù)據(jù)。
那么怎么把Content-type給改了呢?于是我就打開了angular的官網(wǎng),照著改一下請求頭:
$http({ method: 'POST', url: '1.php', data: { id : 1 } headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (data) { console.log(data); });
于是輸出結(jié)果為:{"{\"test\":1}":""},還是有問題。對象并沒有自動地序列化(jQuery用習(xí)慣了都快忘了居然還有這個問題?。?/p>
那么解決方案有:
1.不寫成對象的形式,直接寫字符串:
$http({ method: 'POST', url: '1.php', data: 'test=1', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (data) { console.log(data); });
2.重寫angular中transformRequest,自己寫一個轉(zhuǎn)換方法:
$http({ method: 'POST', url: '1.php', data: $scope.data, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, transformRequest: function ( data ) { var str = ''; for( var i in data ) { str += i + '=' + data[i] + '&'; } return str.substring(0,str.length-1); } }).success(function (data) { console.log(data); });
3.重寫angular中的transformRequest,簡單粗暴地把jquery拿過來:
$http({ method: 'POST', url: '1.php', data: $scope.data, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, transformRequest: function ( data ) { return $.param(data); } }).success(function (data) { console.log(data); });
4.修改默認(rèn)的transformations(這個不太熟,先看一眼官網(wǎng)上怎么說的):
Default Transformations
The $httpProvider provider and $http service expose defaults.transformRequest and defaults.transformResponse properties. If a request does not provide its own transformations then these will be applied. You can augment or replace the default transformations by modifying these properties by adding to or replacing the array. Angular provides the following default transformations: Request transformations ($httpProvider.defaults.transformRequest and $http.defaults.transformRequest): If the data property of the request configuration object contains an object, serialize it into JSON format. Response transformations ($httpProvider.defaults.transformResponse and $http.defaults.transformResponse): If XSRF prefix is detected, strip it (see Security Considerations section below). If JSON response is detected, deserialize it using a JSON parser.
然后照抄:
app.config(['$httpProvider', function ( $httpProvider ) { $httpProvider.defaults.transformRequest = function ( data ) { var str = ''; for( var i in data ) { str += i + '=' + data[i] + '&'; } return str.substring(0,str.length-1); } }]);
<code class="language-javascript">$http({ method: 'POST', url: '1.php', data: $scope.data, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (data) { console.log(data); });</code>
以上這篇快速解決angularJS中用post方法時后臺拿不到值的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
AngularJS基礎(chǔ) ng-include 指令示例講解
本文主要介紹AngularJS ng-include 指令,這里對ng-include 指令的知識做了詳細(xì)整理介紹,有需要的朋友可以參考下2016-08-08基于Angular.js實現(xiàn)的觸摸滑動動畫實例代碼
這篇文章主要介紹了基于Angular.js實現(xiàn)的觸摸滑動動畫實例代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-02-02AngularJS 應(yīng)用身份認(rèn)證的技巧總結(jié)
這篇文章主要介紹了AngularJS 應(yīng)用身份認(rèn)證的技巧總結(jié),具有一定的參考價值,有需要的可以了解一下。2016-11-11Angular.js ng-file-upload結(jié)合springMVC的使用教程
這篇文章主要給大家介紹了關(guān)于Angular.js文件上傳控件ng-file-upload結(jié)合springMVC的使用教程,文中通過示例代碼介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-07-07使用AngularJS來實現(xiàn)HTML頁面嵌套的方法
這篇文章主要介紹了使用AngularJS來實現(xiàn)HTML頁面嵌套的方法,主要用到了AngularJS中的ng-include指令,需要的朋友可以參考下2015-06-06