最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sending a JSON to server and retrieving a JSON in return, without JQuery - Stack Overflow

programmeradmin9浏览0评论

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.

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.

Share Improve this question edited Apr 27, 2016 at 9:25 Damjan Pavlica 33.9k10 gold badges75 silver badges78 bronze badges asked Jun 28, 2014 at 15:46 Jérôme VerstryngeJérôme Verstrynge 59.5k95 gold badges294 silver badges466 bronze badges 10
  • You need to use XMLHttpRequest. The name notwithstanding, you can use it for JSON data (and that is actually how jQuery does it in the background). – elixenide Commented Jun 28, 2014 at 15:48
  • 2 I would POST the data. Have a look at this: youmightnotneedjquery.com. It shows how you can get/post data with vanilla JS. – HaukurHaf Commented Jun 28, 2014 at 15:59
  • 1 @Ed Cottrell The referenced question has nothing to do with this one. The reference is taking about (JUST) sending an ajax request, which is a quite general thing. This one is asking for sending but and receiving JSON in pure JavaScript. Furthermore, in order to send this JSON back, you have to know how to solve this part of the problem on the server-side which is another thing not mentioned on referenced question. – hex494D49 Commented Jul 1, 2014 at 12:32
  • 1 @Ed Cottrell The question you referred to does not have an approved answer and uses old methods to create the Ajax request. It does not provide a full answer to this question. My question is more subtle than a traditional Ajax POST or GET. You missed the point. – Jérôme Verstrynge Commented Jul 1, 2014 at 14:24
  • 1 @JVerstry onreadystatechange is what you use to emulate onload, as shown by the accepted answer below. For parsing, you just use JSON.parse() (again, as shown in the answer), but I was assuming that you already knew that since you mentioned stringifying in the question. I have tried to help you by pointing you to not 1 but 2 questions covering these points. There's obviously some difference -- rarely are 2 questions exactly identical -- but it's trivial if you already know how to stringify and parse JSON. That said, since you and @hex494D49 disagree, I am nominating this for reopening. – elixenide Commented Jul 1, 2014 at 15:00
 |  Show 5 more comments

2 Answers 2

Reset to default 290

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": "[email protected]", "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": "[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();

Handling data in JSON format on the server-side using PHP

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

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 Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

Using new api fetch:

const dataToSend = JSON.stringify({"email": "[email protected]", "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}`)                
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

发布评论

评论列表(0)

  1. 暂无评论