方案一:Content-Type: "application/json"
首先,我們先看下,XMLHttpRequest 請求頭的默認編碼方式是什么。
JS 部分
復制代碼var xhr = new plus.net.XMLHttpRequest(); xhr.onreadystatechange = function() { if( xhr.readyState==4 && xhr.status==200 ) { console.log(xhr.responseText); } } var json = { name: "Eric", password: "123456" }; xhr.open("POST","http://www.xxx.com/api.php"); xhr.send(JSON.stringify(json)); // post 數據只能是字符串
PHP 部分
復制代碼<?php
// 返回請求頭的編碼方式和 name 的值 $header = $_SERVER["CONTENT_TYPE"]; $name = $_POST["name"]; echo '{"header":"'.$header.'","name":"'.$name.'"}'; ?>
返回結果:{"header":"text/plain;charset=utf-8","name":""}
很顯然,$_POST["name"] 沒有取到數據。
雖然他說的是 mui.ajax 方式,但是思路都是一樣的,然后,我修改了下代碼。
JS 部分
復制代碼var xhr = new plus.net.XMLHttpRequest(); xhr.onreadystatechange = function() { if( xhr.readyState==4 && xhr.status==200 ) { console.log(xhr.responseText); } } var json = { name: "Eric", password: "123456" }; xhr.open("POST","http://www.xxx.com/api.php"); xhr.setRequestHeader("Content-Type","application/json;charset=utf-8"); xhr.send(JSON.stringify(json)); // post 數據只能是字符串
PHP 部分
復制代碼<?php
// 返回請求頭的編碼方式和 name 的值 $input = file_get_contents('php://input'); $object = json_decode($input); $name = $object->name; echo '{"header":"'.$_SERVER["CONTENT_TYPE"].'","name":"'.$name.'"}'; ?>
返回結果:{"header":"application/json;charset=utf-8","name":"Eric"}
很顯然,數據已經接收到,這種方案確實有效。
雖然確實能解決問題,但我最終沒有采用的原因是:
①. 不夠直接,它不是通過 $_POST[] 方式獲取的數據,后台需要對數據進行解析,無形中增加了工作量
②. 舊項目遷移不友好,如果舊項目之前采用的是 $_POST[] 方式,后台接口改動會很大
.
方案二:Content-Type: "application/x-www-form-urlencoded"
首先,后台(php)使用 $_POST[] 獲取數據,需要滿足兩個條件:
- 設置請求頭,Content-Type: "application/x-www-form-urlencoded"
- 請求數據必須序列化,比如,name=Eric&password=123456
直接上代碼:
JS 部分
復制代碼var xhr = new plus.net.XMLHttpRequest(); xhr.onreadystatechange = function() { if( xhr.readyState==4 && xhr.status==200 ) { console.log(xhr.responseText); } } xhr.open("POST","http://www.xxx.com/api.php"); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); xhr.send("name=Eric&password=123456");
PHP 部分
復制代碼<?php
$header = $_SERVER["CONTENT_TYPE"]; $name = $_POST["name"]; echo '{"header":"'.$header.'","name":"'.$name.'"}'; ?>
返回結果:{"header":"application/x-www-form-urlencoded;charset=utf-8","name":"Eric"}