国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

快速解決angularJS中用post方法時后臺拿不到值的問題

2024-05-06 15:31:41
字體:
來源:轉載
供稿:網友

用angularJS中的$http服務碰到了一個問題:運用$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>

輸出結果為:{"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.8Accept-Encoding: gzip, deflateAccept-Language: zh-CN,zh;q=0.8,ja;q=0.6Cache-Control: no-cacheConnection: keep-aliveContent-Length: 5Content-Type: application/x-www-form-urlencodedCookie: a0537_times=1Host: 127.0.0.1Origin: http://127.0.0.1Pragma: no-cacheReferer: http://127.0.0.1/angularTest/1.htmlUpgrade-Insecure-Requests: 1User-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, deflateAccept-Language: zh-CN,zh;q=0.8,ja;q=0.6Cache-Control: no-cacheConnection: keep-aliveContent-Length: 10Content-Type: application/json;charset=UTF-8Cookie: a0537_times=1Host: 127.0.0.1Origin: http://127.0.0.1Pragma: no-cacheReferer: http://127.0.0.1/angularTest/1.htmlUser-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默認發(fā)送的則是json數(shù)據(jù)。

那么怎么把Content-type給改了呢?于是我就打開了angular的官網,照著改一下請求頭:

$http({ method: 'POST', url: '1.php', data: { id : 1 } headers: {  'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (data) { console.log(data); });

于是輸出結果為:{"{/"test/":1}":""},還是有問題。對象并沒有自動地序列化(jQuery用習慣了都快忘了居然還有這個問題!)

那么解決方案有:

1.不寫成對象的形式,直接寫字符串:

$http({ method: 'POST', url: '1.php', data: 'test=1', headers: {  'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (data) { console.log(data); });            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 上蔡县| 海宁市| 大丰市| 祁连县| 太和县| 齐齐哈尔市| 上林县| 贵南县| 广昌县| 永福县| 高雄县| 乌审旗| 淮阳县| 招远市| 绩溪县| 苏州市| 潞城市| 改则县| 沁源县| 成武县| 香河县| 甘洛县| 朝阳市| 武威市| 汉寿县| 于田县| 平陆县| 博罗县| 霍城县| 清水河县| 峡江县| 威海市| 永顺县| 天峨县| 阳春市| 台东县| 磐石市| 玉环县| 宜宾市| 交口县| 分宜县|