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
        ]);
    }
?>
南无阿弥陀佛,善哉善哉
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值