Pesquisa de site

Javascript: Enviar objeto JSON com Ajax?


Isso é possível?

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

Talvez com: um cabeçalho com content type : application/json?

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

Caso contrário, posso usar:

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

e então JSON.stringify o objeto JSON e envie-o em um parâmetro, mas seria legal enviá-lo desta forma se for possível.

Resposta #1

Com jQuery:

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

Sem 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"}));

Resposta #2

Se você não está usando jQuery, por favor, certifique-se de:

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

E para o lado que recebe em PHP:

 $_POST['json_name'] 

Artigos relacionados