将JSON发送到服务器并在没有JQuery的情况下检索JSON

Jér*_*nge 92 javascript post json get xmlhttprequest

我需要将JSON(我可以将其字符串化)发送到服务器并在用户端检索生成的JSON,而不使用JQuery.

如果我应该使用GET,我如何将JSON作为参数传递?是否存在太长的风险?

如果我应该使用POST,如何onload在GET中设置函数的等价物?

或者我应该使用不同的方法?

备注

这个问题不是关于发送一个简单的AJAX.它不应该作为重复关闭.

hex*_*D49 188

使用POST方法以JSON格式发送和接收数据

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
xhr.send(data);
Run Code Online (Sandbox Code Playgroud)

使用GET方法以JSON格式发送接收数据

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "hey@mail.com", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();
Run Code Online (Sandbox Code Playgroud)

使用PHP在服务器端处理JSON格式的数据

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
Run Code Online (Sandbox Code Playgroud)

HTTP Get请求的长度限制取决于服务器和使用的客户端(浏览器),从2kB到8kB.如果URI比服务器可以处理的长,则服务器应返回414(Request-URI Too Long)状态.

注意有人说我可以使用州名而不是州名; 换句话说,我可以使用xhr.readyState === xhr.DONE而不是xhr.readyState === 4问题是Internet Explorer使用不同的状态名称,因此最好使用状态值.

  • Should be `xhr.status === 200` . (4认同)

Joh*_*ias 13

使用新的 api fetch

const dataToSend = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
let dataReceived = ""; 
fetch("", {
    credentials: "same-origin",
    mode: "same-origin",
    method: "post",
    headers: { "Content-Type": "application/json" },
    body: dataToSend
})
    .then(resp => {
        if (resp.status === 200) {
            return resp.json()
        } else {
            console.log("Status: " + resp.status)
            return Promise.reject("server")
        }
    })
    .then(dataJson => {
        dataReceived = JSON.parse(dataJson)
    })
    .catch(err => {
        if (err === "server") return
        console.log(err)
    })

console.log(`Received: ${dataReceived}`)                
Run Code Online (Sandbox Code Playgroud)
当服务器发送其他状态而不是 200(ok) 时,您需要处理,您应该拒绝该结果,因为如果您将其留空,它将尝试解析 json 但没有解析,因此它会抛出错误

  • 您使用了两次“JSON.stringify”。 (2认同)