Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Instead of sending a list of key/value pairs, I need to send a JSON string as the body of the POST request.
I make this POST request using jQuery's $.ajax function.
How do I set it correctly?

When I say JSON string, I mean something like: {action:'x',params:['a','b','c']} .

This is how I would use this JSON string in PHP on the server:

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

Results in:

stdClass Object
    action = x
    params = Array
        (
    0 = a
    1 = b
    2 = c
        )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
314 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

Hope this helps,

Pete


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...