POST,AJAX和PHP:JSON提交 [英] POST, AJAX, and PHP : JSON submission
问题描述
好,所以这是我的JS/jQuery代码,我的rate.php文件中仅包含一个print_r($_POST)
.问题是,$_POST
接受rated
作为字符串"Array"
,而不是我定义的实际数组.如何纠正此代码,以便PHP将JSON输入识别为正确的数组,而不是字符串?
Ok, so here is my JS/jQuery code, my rate.php file simply has a print_r($_POST)
in it. The problem is, the $_POST
is accepting rated
as the string "Array"
, rather than the actual array as I have defined it. How do I correct this code so PHP will recognize the JSON input as a proper array, rather than a string?
var rated = {"key" : key , "value" : value};
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"rated" : rated
},
success: function(data) {
alert(data);
}
});
这是我得到的输出消息:
This is the output message I'm getting:
数组 ( [评分] =>数组 )
致命错误:只有变量可以通过引用在 X
行上的 .../ajax/rate.php 中传递>
Array ( [rated] => Array )
Fatal error: Only variables can be passed by reference in .../ajax/rate.php on line X
实际上,rated
有更多的变量,但是它们都不是数组(因此它们没有问题),因此为了简洁起见,我将它们从上面的代码中删除了.
There are actually more variables that rated
, but none of them are arrays (thus there isn't an issue with them), so I cut them out of the code above for brevity sake.
推荐答案
通过ajax将JSON数据传递到您的php脚本时,我建议对字符串进行JSON编码,然后在服务器端进行解析.
When passing JSON data to your php script through ajax I would recommend string encoding the JSON data and then parsing it on the server side.
var rated = {"key" : key , "value" : value};
var rated_encoded = JSON.stringify(rated);
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"rated" : rated_encoded
},
success: function(data) {
alert(data);
}
});
然后,您应该可以使用$ _POST以及任何其他标量值来访问PHP脚本中的POST变量.在服务器端拥有JSON字符串"rating_encoded"后,请使用PHP的json_decode()将其解析为关联数组.
Then you should be able to access the POST variable in your PHP script using $_POST as with any other scalar value. Once you have the JSON string 'rating_encoded' on the server-side, parse it to an associative array using PHP's json_decode().
if(isset($_POST["rated"])){
$rated_json = $_POST["rated"];
$JSONArray = json_decode($rated_json, true); //returns null if not decoded
//Values can now be accessed like standard PHP array
if($JSONArray !== null){
$key = $JSONArray["key"];
$value = $JSONArray["value"];
}
}
我发现此方法对于将javascript对象数据传输到服务器(反之亦然)非常有效(使用PHP的json_encode()将PHP数组转换为有效的javascript对象)
I've found that this method is very effective for transferring javascript object data to the server and vice versa (using PHP's json_encode() to translate PHP arrays into valid javascript objects)
这篇关于POST,AJAX和PHP:JSON提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!