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

问题描述 投票:78回答:2

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

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

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

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

备注

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

javascript json post get xmlhttprequest
2个回答
167
投票

使用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": "[email protected]", "password": "101010"});
xhr.send(data);

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

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "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();

使用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);
?>

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

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


0
投票

使用新的api fetch

const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataRecieved=""; 
fetch("",{credentials:'same-origin',mode:'same-origin',method:"post",body:dataToSend})
              .then(resp => {
                if(resp.status==200){
                   return resp.json()
                }else{
                    console.log("Status: "+resp.status);
                    return Promise.reject("server")
                }
              })
           .then(dataJson =>{
                 dataToRecieved = JSON.parse(dataJson);
             })
              .catch(err =>{
                if(err=="server")return
                console.log(err);
            })
            
             
You need to handle when server sends other status rather than 200(ok), you should reject that result because if you were to left it in blank, it will try to parse the json but there isn't, so it will throw an error
© www.soinside.com 2019 - 2024. All rights reserved.