我想这与正常情况相反。我希望将 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',
))
)
即使我希望它是一些字符串。