在没有JQuery的情况下将JSON发送到服务器并获取JSON作为回报

在没有JQuery的情况下将JSON发送到服务器并获取JSON作为回报,第1张

在没有JQuery的情况下将JSON发送到服务器并获取JSON作为回报 使用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=" + enpreURIComponent(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_depre(stripslashes(file_get_contents("php://input")));// build a PHP variable from JSON sent using GET method$v = json_depre(stripslashes($_GET["data"]));// enpre the PHP variable to JSON and send it back on client-sideecho json_enpre($v);?>

HTTP
Get请求的长度限制取决于所使用的服务器和客户端(浏览器),范围从2kB-8kB。如果URI的长度超过服务器的处理能力,则服务器应返回414(请求URI太长)状态。

注意 有人说我可以使用状态名称代替状态值。换句话说,我可以使用

xhr.readyState ===xhr.DONE
代替。
xhr.readyState === 4
问题是Internet Explorer使用不同的状态名称,因此最好使用状态值。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5440290.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存