Javascript: Wyślij obiekt JSON za pomocą Ajax?

Czy to możliwe?

xmlHttp.send({
    "test" : "1",
    "test2" : "2",
});

Może z: nagłówkiem z content type : application/json?:

xmlHttp.setRequestHeader('Content-Type', 'application/json')

W Przeciwnym Razie mogę użyć:

xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

A następnie JSON.stringify obiekt JSON i wysłać go w parametrze, ale fajnie byłoby wysłać go w ten sposób, jeśli to możliwe.

Author: Adam, 2011-06-21

3 answers

Z jQuery:

$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });

Bez jQuery:

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));
 267
Author: Nathan Romano,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 18:50:35

Jeśli nie używasz jQuery, upewnij się:

var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

I dla końca odbioru php:

 $_POST['json_name'] 
 29
Author: shantanu chandra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-18 02:56:10

Dodanie Json.stringfy wokół json naprawiło problem

 0
Author: user3310115,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-09 23:02:54