0

试图将 javascript 对象传递给 php 并收到此错误。我究竟做错了什么?

var address = {};

address.whatever = "asdf";

$.ajax({
            type: 'post',
            url: '/resources/scripts/php/whatever.php',
            data: 'address=' + JSON.stringify(address),
            success: function(returnedData){
                console.log(returnedData);
            },
            error: function (xhr, tst, err) {
                console.log(err);
            },          
        });

php

$whatever = json_decode($_POST['address']);
 echo json_decode($address);

安慰: null

感谢您的任何见解!

4

4 回答 4

1
$whatever = json_decode($_POST['address']);
echo json_decode($address);

应该:

 echo $_POST["whatever"];

data: 'address=' + JSON.stringify(address),

应该:

 data: JSON.stringify(address),
于 2012-10-24T17:38:16.863 回答
0
$.ajax({
            type: 'post',
            url: '/resources/scripts/php/whatever.php',
            data: {address : address},
            success: function(returnedData){
                console.log(returnedData);
            },
            error: function (xhr, tst, err) {
                console.log(err);
            }          
        });

尝试这个

于 2012-10-24T17:35:45.590 回答
0

尝试

$.ajax({
        type: 'post',
        url: '/resources/scripts/php/whatever.php',
        data: {'address' : JSON.stringify(address)},
        success: function(returnedData){
            console.log(returnedData);
        },
        error: function (xhr, tst, err) {
            console.log(err);
        },          
    });

PHP:

 $address = json_decode($_POST['address']);
 echo $address['whatever'];
于 2012-10-24T17:37:04.770 回答
0

无需 JSON.stringify。jQuery 会为您处理它。

和:

$.ajax({
    type: 'post',
    url: '/resources/scripts/php/whatever.php',
    data: {address: address},
    success: function(returnedData){
        console.log(returnedData);
    },
    error: function (xhr, tst, err) {
        console.log(err);
    },
});

您可以使用:

echo $_POST['address']['whatever'] // output asdf
于 2012-10-24T17:37:53.537 回答