我正试图通过AJAX$.post将一个关联数组发送到php。这是我的代码:
var request = {
action: "add",
requestor: req_id,
...
}
var reqDetails = $("#request_details").val();
switch(reqDetails){
case 1:
request[note] = $("#note").val();
break;
...
}
if(oldRequest()){
request[previousID] = $("old_id").val();
}
$('#req_button').toggleClass('active');
$.post("scripts/add_request.php", {
request_arr: JSON.stringify(request)
}, function(data){
console.log(data);
$('#req_button').toggleClass('active');
}, 'json');
我只是想在我的php脚本中读取接收到的数据:
echo json_decode($_POST["request_arr"]);
但它不起作用。我是js的新手,我不知道自己做错了什么。
查看下面的链接以获取您的参考
从JavaScript/jQuery 向php发送数组
步骤1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
步骤2
php文件如下所示:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
步骤3
成功功能
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
您已经在使用"json"作为dataType,因此您不应该对数据应用"stringify"操作。
你能直接试试request_arr: request
而不是request_arr: JSON.stringify(request)
吗?