微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php与ajax交互

html
<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8" />
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script src="ajax.js"></script>
</head>
<body>
</body>
</html>
ajax.js
'use strict';

//jquery发送json数据
// $.ajax({
//     url: 'server.PHP',
//     method: 'POST',
//     dataType: 'json',
//     contentType: 'application/json;charset=UTF-8',
//     data:JSON.stringify({"id":1}),
//     success:function(data, status){
//         console.log(data);
//     }
// });

//原生ajax发送json数据
var xhr = new XMLHttpRequest();

//如果状态改变时,执行的回调函数
xhr.onreadystatechange = function() {
    //如果状态为4,说明已经完成
    if (xhr.readyState == 4) {
        //如果状态码为正常
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
            //把json字符串转换为对象
            var x = JSON.parse(xhr.responseText);
            //获取一下x变量的数据类型
            console.log(typeof x);
            //输出id的键值
            console.log(x.mycode);
        } else {
            console.log(xhr.status);
        }
    }
}

//请求方法为post,url为server.PHP,异步通信
xhr.open("POST", "server.PHP", true);
//设置一下发送给服务器的头部
//请求报文的内容类型为json,字符集为utf-8
xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");
//把json对象转换为字符串
xhr.send(JSON.stringify({"id":1}));
server.PHP
<?PHP
	//获取原始流
    $postdata = file_get_contents("PHP://input");
    //如果有数据
    if (isset($postdata)) {
        //把json字符串转换为对象
        $request = json_decode($postdata);
        //访问json对象
        $id = $request->id;
        //把json格式转换为字符串
        echo json_encode([
            "mycode" => $id
        ]);
    }
?>
南无阿弥陀佛,善哉善哉

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐