使用ajax 进行post提交json数据到后台php,但是后台php收不到数据。

当 contentType 为 application/x-www-form-urlencoded 时(默认值)
才能用 $_POST 得到传入的数据。但是使用 application/json;charset=utf-8
不是 php 所能识别的类型声明,不能替你解析。所以只能用 php://input 取得,并用 parse_str 自行解析

而形如 a=1&b=2&c=3 这样的数据,分明就不是 json 格式。即便 php 能识别 application/json 类型,也不能解析你这样的数据。

当然还有一种方式:

前台(部分):

$.ajax({
url:'http://127.0.0.1/dist/example/qian.php',
type:'POST',
    contentType:'application/json;charset=utf-8',
dataType:'json',
    data: JSON.stringify({images:"dadad"}),

后台(部分):

header('Content-type: application/json');

$data = json_decode(file_get_contents("php://input"), true);
$user = $data["images"];

猜你喜欢

转载自blog.csdn.net/daixiangzi/article/details/80480326