栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在没有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": "hey@mail.com", "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": "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();

使用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使用不同的状态名称,因此最好使用状态值。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464794.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号