简体   繁体   中英

JSON string in ajax post request content-type application/formdata vs application/json

It might be a very basic or silly question but its indeed a deep concept question.

If I have a ajax post request like (client side):

var response = {};
        response['key'] =  value;
        response['key2'] = value2;

$.ajax({
            type: "POST",
            url: "xyz.php",
            data: JSON.stringify(response),
            dataType: "html",
            success: function (result) {}
        });

And on server side I do

$a = json_decode($data, true);

And I can $a['abc'] and do rest of my work.

Question is since I have not specified contentType as application/json in ajax request the jquery would send the data as application/form-data which means I should access it via $_POST['data'] and don't do json_decode. Right?

Vise Versa If I send json string on client side with content type application/json then on server side I can on access it via json_decode and not $_POST[]. Right?

I'm quiet confused on this basic issue. Can anyone provide a good explanation on this???

Note: My server returns the json encoded data in return. And Im using slim framework so I can access the post body as $app->request->getBody();

If you want all your data to be accessible through a single variable on the server side, you'll want to do something like this:

JS:

$.ajax({
        type: "POST",
        url: "xyz.php",
        data: {'data', JSON.stringify(response)},
        dataType: "html",
        success: function (result) {}
    });

PHP:

$a = json_decode($_POST['data'], true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM