Jak ustawić surowe ciało w Jquery Ajax?

Zamiast wysyłać listę par klucz / wartość, muszę wysłać łańcuch JSON jako treść żądania POST.
Robię to żądanie POST używając $jQuery.funkcja ajax.
Jak poprawnie ustawić?

Kiedy mówię JSON string, mam na myśli coś w stylu: {action:'x',params:['a','b','c']}.

Oto jak użyłbym tego ciągu JSON w PHP na serwerze:

var_dump(json_decode(file_get_contents('php://input')));

Wyniki w:

stdClass Object
    action = x
    params = Array
        (
    0 = a
    1 = b
    2 = c
        )
Author: rstackhouse, 2012-01-31

2 answers

Try:

$.ajax('url',{
    'data': JSON.stringify(yourJSONObject), //{action:'x',params:['a','b','c']}
    'type': 'POST',
    'processData': false,
    'contentType': 'application/json' //typically 'application/x-www-form-urlencoded', but the service you are calling may expect 'text/json'... check with the service to see what they expect as content-type in the HTTP header.
});

Mam nadzieję, że to pomoże,

Pete

 85
Author: pete,
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
2012-10-04 19:08:12

Jeśli nie podasz klucza, myślę, że będzie on wysyłany jako ciało bez klucza, jak

$.ajax({
data:JSON.stringify({action:'x',params:['a','b','c']})
});
 4
Author: Rafay,
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
2012-01-31 17:55:07