PHP接收前端傳值各種情況整理


PHP接收前端傳值各種情況整理

服務端代碼:


header('Access-Control-Allow-Origin:*');
var_dump($_POST);
exit;

情況

1) 傳null


$.post('http://xxxxx.xx/index.php', {
    "test": null
}, function(data, status) {
    console.log(data);
});

結果:


array(1) {
  ["test"]=>
  string(0) ""
}

2) 傳''

代碼:


$.post('http://xxxxx.xx/index.php', {
    "test": ''
}, function(data, status) {
    console.log(data);
});

結果:


array(1) {
  ["test"]=>
  string(0) ""
}

3) 傳'[]'


$.post('http://xxxxx.xx/index.php', {
    "test": '[]'
}, function(data, status) {
    console.log(data);
});

結果:


array(1) {
  ["test"]=>
  string(2) "[]"
}

4) 傳[]


$.post('http://xxxxx.xx/index.php', {
    "test": []
}, function(data, status) {
    console.log(data);
});

結果:


array(0) {
}

5) 傳2個[]


$.post('http://xxxxx.xx/index.php', {
    "test": [],
    "test2": []
}, function(data, status) {
    console.log(data);
});

結果:


array(0) {
}

6) 傳{}


$.post('http://xxxxx.xx/index.php', {
    "test": {}
}, function(data, status) {
    console.log(data);
});

結果:


array(0) {
}

7) 傳2個{}


$.post('http://xxxxx.xx/index.php', {
    "test": {},
    "test2": {}
}, function(data, status) {
    console.log(data);
});

結果:


array(0) {
}

8) 傳1個{}加1個非空對象


$.post('http://xxxxx.xx/index.php', {
    "test": {},
    "test2": {"a": 1}
}, function(data, status) {
    console.log(data);
});

結果:


array(1) {
  ["test2"]=>
  array(1) {
    ["a"]=>
    string(1) "1"
  }
}

9) 傳[{}]


$.post('http://xxxxx.xx/index.php', {
    "test": [{}]
}, function(data, status) {
    console.log(data);
});

結果:


array(0) {
}

10) 傳[[{}]]


$.post('http://xxxxx.xx/index.php', {
    "test": [[{}]]
}, function(data, status) {
    console.log(data);
});

結果:


array(0) {
}

11) 傳'nil'


$.post('http://xxxxx.xx/index.php', {
    "test": 'nil'
}, function(data, status) {
    console.log(data);
});

結果:


array(1) {
  ["test"]=>
  string(3) "nil"
}

12) 傳0


$.post('http://xxxxx.xx/index.php', {
    "test": 0
}, function(data, status) {
    console.log(data);
});

結果:


array(1) {
  ["test"]=>
  string(1) "0"
}

13) 傳'null'


$.post('http://xxxxx.xx/index.php', {
    "test": 'null'
}, function(data, status) {
    console.log(data);
});

結果:


array(1) {
  ["test"]=>
  string(4) "null"
}

用抓包工具發現

  1. http請求里面並不會發送"無效的"字段——[]和{},所以不是PHP丟棄了,而是沒收到;
  2. 當傳的值是js里的null,會轉換成空字符串,http請求里面是test=,所以PHP接收到的test是個空字符串;
  3. http協議不能表示值是什么類型,所以PHP只能什么都當做string

總結:

  1. PHP對於接收到的每一個值,會轉換成字符串變量
  2. PHP對於接收到的,之所有會接收不到是因為被一系列規則過濾掉了

以上結論是在jQ和PHP7之下驗證的,其他環境不一定保證正確,之后可以試驗使用CURL發送數據試試。

TODO:

  • [ ] 用CURL發送POST測試

原文鏈接:https://my.oschina.net/wiiilll/blog/3002507


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM