我正在尝试通过 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新手,我不知道我做错了什么。
最佳答案
查看以下链接以供引用
Sending an array to php from JavaScript/jQuery
第 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);
}
关于javascript - AJAX jquery json发送数组到php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29391378/