Javascript: Skicka JSON-objekt med Ajax?
Är detta möjligt?
xmlHttp.send({
"test" : "1",
"test2" : "2",
});
Kanske med: en header med content type : application/json?:
xmlHttp.setRequestHeader('Content-Type', 'application/json')
Annars kan jag använda:
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
och sedan JSON.stringify JSON-objektet och skicka det i en parameter, men det skulle vara coolt att skicka det på detta sätt om det är möjligt.
Svar #1
Med jQuery:
$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });
Utan 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"}));
Svar #2
Om du inte använder jQuery, se då till att:
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);
Och för PHP-mottagarsidan:
$_POST['json_name']
