php和js传递json

新鲜出炉的php和js ajax原生请求json格式传递。


先上实现代码

  1. js发送json格式的消息给php:

    // getData.js
    let user = {
        name: zhang,
        email: [email protected]
    };
    let url = 'http://xxx.xxx.com';
    let post = new Promise(function(resolve, reject) {
        let request = new XMLHttpRequest();
        request.open("POST", url);
        request.responseType = "json";
        // 设置Content-type
        request.setRequestHeader('Content-type', 'application/json');
        // 处理json数据并send
        request.send(JSON.stringify(user));
        request.onload = function() {
            if (this.status === 200) {
                resolve(this.response);
            } else {
                reject(this.status);
            }
        }
    });
    post.then(...) //省略处理
    
  2. php 接收以及发送json格式给js

    // sendData.php
    // 接收来自前端请求带来的json数据并decode成php数组
    $user = json_decode(file_get_contents("php://input"));
    ... 
    $result = array('code' => '200', 'message' => 'success', 'data' => array(1, 2, 3));
    // 对数组进行encode并发送给前端
    echo json_encode($result);
    

接下来介绍关键函数

  1. 接下来介绍javascript的JSON.stringify
    不知道该说啥,mdn地址奉上。

  2. php的两个函数json_encode和json_decode
    json_encode是对json编码,用于php数组–>json字符串(向前端传数据)
    json_decode是对json解码,用于将json字符串–>php数组(接收前端数据)

猜你喜欢

转载自blog.csdn.net/tingyugetc11/article/details/81188519
今日推荐