<h1>PHP接收前端传值各种情况整理</h1> <h2>服务端代码:</h2>
1header('Access-Control-Allow-Origin:*');
2var_dump($_POST);
3exit;
4
<h2>情况</h2> <h3>1) 传null</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": null
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
1array(1) {
2 ["test"]=>
3 string(0) ""
4}
5
<h3>2) 传''</h3> <p>代码:</p>
1$.post('http://xxxxx.xx/index.php', {
2 "test": ''
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
1array(1) {
2 ["test"]=>
3 string(0) ""
4}
5
<h3>3) 传'\[\]'</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": '[]'
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
1array(1) {
2 ["test"]=>
3 string(2) "[]"
4}
5
<h3>4) 传\[\]</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": []
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
<h3>5) 传2个\[\]</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": [],
3 "test2": []
4}, function(data, status) {
5 console.log(data);
6});
7
<p>结果:</p>
<h3>6) 传{}</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": {}
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
<h3>7) 传2个{}</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": {},
3 "test2": {}
4}, function(data, status) {
5 console.log(data);
6});
7
<p>结果:</p>
<h3>8) 传1个{}加1个非空对象</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": {},
3 "test2": {"a": 1}
4}, function(data, status) {
5 console.log(data);
6});
7
<p>结果:</p>
1array(1) {
2 ["test2"]=>
3 array(1) {
4 ["a"]=>
5 string(1) "1"
6 }
7}
8
<h3>9) 传\[{}\]</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": [{}]
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
<h3>10) 传\[\[{}\]\]</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": [[{}]]
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
<h3>11) 传'nil'</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": 'nil'
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
1array(1) {
2 ["test"]=>
3 string(3) "nil"
4}
5
<h3>12) 传0</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": 0
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
1array(1) {
2 ["test"]=>
3 string(1) "0"
4}
5
<h3>13) 传'null'</h3>
1$.post('http://xxxxx.xx/index.php', {
2 "test": 'null'
3}, function(data, status) {
4 console.log(data);
5});
6
<p>结果:</p>
1array(1) {
2 ["test"]=>
3 string(4) "null"
4}
5
<p>用抓包工具发现</p> <ol> <li>http请求里面并不会发送<code>"无效的"</code>字段——\[\]和{},所以不是PHP丢弃了,而是没收到;</li> <li>当传的值是js里的<code>null</code>,会转换成空字符串,http请求里面是<code>test=</code>,所以PHP接收到的test是个空字符串;</li> <li>http协议不能表示值是什么类型,所以PHP只能什么都当做string</li> </ol> <h2>总结:</h2> <ol> <li>PHP对于接收到的每一个值,会转换成字符串变量</li> <li>PHP对于接收到的,之所有会接收不到是因为被一系列规则过滤掉了</li> </ol> <p>以上结论是在jQ和PHP7之下验证的,其他环境不一定保证正确,之后可以试验使用CURL发送数据试试。</p> <h2>TODO:</h2> <ul> <li>\[ \] 用CURL发送POST测试</li> </ul>
原文链接:https://my.oschina.net/wiiilll/blog/3002507