XMLHttpRequest 发送 post 请求,php 接收不到数据的解决方案

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了XMLHttpRequest 发送 post 请求,php 接收不到数据的解决方案脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

方案一: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"}

脚本宝典总结

以上是脚本宝典为你收集整理的XMLHttpRequest 发送 post 请求,php 接收不到数据的解决方案全部内容,希望文章能够帮你解决XMLHttpRequest 发送 post 请求,php 接收不到数据的解决方案所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: