I need to send a JSON (which I can stringify) to the server and to retrieve the resulting JSON on the user side, without using JQuery.

If I should use a GET, how do I pass the JSON as a parameter? Is there a risk it would be too long?

If I should use a POST, how do I set the equivalent of an onload function in GET?

Or should I use a different method?

REMARK

This question is not about sending a simple AJAX. It should not be closed as duplicate.

推荐答案

Sending and receiving data in JSON format using POST method

// 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);

Sending and receiving data in JSON format using GET method

// 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();

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

<?php
// 使用PHP在服务器端处理JSON格式的数据
//
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);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

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

Json相关问答推荐

如何将加权边列表导出到JSON树?

使用 jq 从带有转义反斜杠字符的嵌套 JSON 中提取数据

Jolt Spec 跳过数组中的第一个元素

迭代powershell双维json对象

正向闪烁后的微调值

在 PostgreSQL 中 Select 分层 JSON 作为表

派生类的属性没有得到价值

从字节解码 JSON 数据,将 float 值更改为 int

从 PowerShell 编辑 Windows 终端配置文件设置 JSON

JQ 中的样本标准偏差

SwiftUI:如何使用 0 索引数组键为 JSON 添加类型

现代浏览器一次可以处理多少个 HTML 元素?

未捕获的类型错误:无法读取 null 的属性props

使用 @ResponseBody 自定义 HttpMessageConverter 来做 Json 事情

将序列化表单的数据转换为 json 对象

与classic 规范化表相比,postgres JSON 索引是否足够高效?

春天:返回@ResponseBodyResponseEntity>

如何向 json IAM 策略添加 comments ?

如何使用 Jackson 的 objectMapper 反序列化接口字段?

我应该如何在 JSON 中表示表格数据?