我已经尝试了几乎所有的建议,但它不起作用。当我使用 arr['id']
alert
我的数组时,我的 id
在 JavaScript 函数中正常工作。但是,当我在不同的 PHP 文件上尝试 $_POST['id']
(我使用了 AJAX 并指定了 URL)时,出现了错误。
脚本文件.php:
<script>
function detailsmodal(cid, pid) {
var arr = { "cid": cid, "pid": pid };
jQuery.ajax({
url: '/frontend/include/detailsmodal.php',
method: "post",
data: arr,
success: function(data) {
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function() {
alert("something went wrong");
}
});
}
详细信息模态.php
<?php
echo $_POST['cid'];
?>
最佳答案
您可以尝试将数据作为 json 发送,如下所示:
$.ajax({
type: "POST",
url: "/frontend/include/detailsmodal.php",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ cid: cid, pid: pid }),
success: function(data) {
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function() {
alert("something went wrong");
}
});
对于解码,您可以使用 javascript JSON.parse
var myObj = JSON.parse(this.responseText);
或
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["cid"];
关于javascript - jQuery AJAX 发送的 JSON 对象的 post 方法中未定义索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46524469/