简体   繁体   中英

php, ajax and json encoding/decoding

I'm using jQuery and jquery-json to post data to a PHP script.

       $.post('<?php echo url_for('/ajax.php'); ?>', 'data=' + $.toJSON(order), function (response) {

                if (response == "success") {
                    $("#respond").html('<div class="success">Item Saved!</div>').hide().fadeIn(1000);
                    setTimeout(function () {
                        $('#respond').fadeOut(1000);
                    }, 2000);
                }
         })

If I console.log(order) I get the following JOSN:

{"details":[{"template_id":"25","font_size":"22"}]}

In my ajax.php file I have:

$data = json_decode($_POST["data"]);
var_dump($data);exit;

Which returns 'NULL'

But when I have the following code:

$data = $_POST["data"];
var_dump($data);exit;

It returns:

string(61) "{\"details\":[{\"template_id\":\"25\",\"font_size\":\"26\"}]}"

Is there any reason why it is escaped?

What is the easiest way to decode this?

Thanks

you may need to disable magic_quotes_gpc in your php.ini or .htaccess file which is adding the slashes to your post variables.

Or you could just call stripslashes on $_POST['data'] like so:

$data = json_decode(stripslashes($_POST["data"]));

You need to add dataType: 'json' to your ajax call.

$.ajax({
    url: url,
    type: 'post',
    dataType: 'json',
    data: $.toJSON(order),
    async: true,
    success: function (data) {

      if (data.response) {
        $("#respond").html('<div class="success">Item Saved </div>').hide().fadeIn(1000);
                    setTimeout(function () {
                        $('#respond').fadeOut(1000);
                    }, 2000);

      }

    }

});

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