首页 > 语言 > JavaScript > 正文

快速解决angularJS中用post方法时后台拿不到值的问题

2024-05-06 15:31:41
字体:
来源:转载
供稿:网友

用angularJS中的$http服务碰到了一个问题:运用$http.post方法向后台传递数据时,后台的php页面获取不到data参数传过来的值。

不论是这种姿势:

$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);?>

输出为一个空数组。为了测试php本身是不是真的获取不到值,我就写了个表单测试下:

<form action="1.php" method="post"> <input type="text" name="tid"> <input type="submit" value="submit"></form>

输出结果为:{"tid":"2"},也就是说表单里的值是可以获取的,但是用ajax发送的数据获取不了!

那么表单数据和ajax发送的post数据之间有什么差异呢?于是我悄悄瞄一眼请求头...

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发送的数据的请求头部:

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

问题一下子就出来了!表单发送的文本类型是表单类型,而angular的ajax默认发送的则是json数据。

那么怎么把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); });            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选