在 PHP 中以 JSON 形式接收 jQuery JSON 数据


Receiving jQuery JSON data as JSON in PHP

我想这与正常情况相反。我希望在PHP中以字符串形式接收数据,其中包含JSON,并且我希望jQuery对数据进行编码。

目前 PHP 会自动将数据解码为数组。

PHP 5.3.10 ( 托管 )。

<?php
if( isset( $_REQUEST['arr']))
{
    $arr = $_REQUEST['arr'];
    $obj = $_REQUEST['obj'];   
    $res = "arr is of type ".gettype( $arr).", var_export (".var_export( $arr, true).")'n" 
         . "obj is of type ".gettype( $obj).", var_export (".var_export( $obj, true).")'n";  
    die( json_encode( $res ));
    exit;
} 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
<script>
$(document).ready(function(){
    $("#csubmit").click( function() {
        var arr = new Array("one","two");
        var obj = { "one":1, "two":2 };
        var data ={ "arr" :arr, "obj" : obj };
        $.ajax({
            type: "POST",
            cache: false,
            data: data,
            dataType : "json",
                complete : function( jqXHR, textStatus ) {
                    if( textStatus != 'success' )
                        alert("Network error ("+textStatus+"/"+jqXHR.responseText+")");
                }
        }).done( function( data ) {
            alert("Got back:("+data+")");
        });
        return false;
    });
});
</script>
</head>
<body>
<form><input type="submit" value="click" id="csubmit"></form>
</body>
</html>

结果始终是

Got back:(arr is of type array, var_export (array (
  0 => 'one',
  1 => 'two',
))
obj is of type array, var_export (array (
  'one' => '1',
  'two' => '2',
))
)

即使我希望它是几根字符串。

当您接受回 JSON 时,您正在发送正常的形式编码数据 ( application/x-www-form-urlencoded ):

arr%5B%5D=one&arr%5B%5D=two&obj%5Bone%5D=1&obj%5Btwo%5D=2

arr[]=one&arr[]=two&obj[one]=1&obj[two]=2

你可以通过 PHP 确认这一点

$raw_input = file_get_contents("php://input");
echo urldecode($raw_input);

除非你在JavaScript中显式转换,否则你不会发送{"arr":["one","two"],"obj":{"one":1,"two":2}},正如其他人所指出的那样。

略AJAX请求中的dataType: 'json',将数据编码为jQuery中的JSON,并将其传递给PHP。

这应该行得通。

您可以在将

JavaScript 对象发送到服务器之前将其编码为 JSON。然后,您必须手动解码 json 以将其用作数组。在您的 ajax 方法中执行以下操作。

   data : JSON.stringify(data),

编辑:

JSON 对象在较新的浏览器中原生受支持。对于那些不支持它的人,您仍然可以通过包含 http://json.org 中的 json2.js来实现该功能。

有关 JSON 的更多信息,请访问 https://developer.mozilla.org/En/Using_native_JSON