javascript - jQuery AJAX 发送的 JSON 对象的 post 方法中未定义索引

标签 javascript php jquery json ajax

我已经尝试了几乎所有的建议,但它不起作用。当我使用 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/

相关文章:

javascript - 为什么一个功能有效而另一个功能无效? (JavaScript)

javascript - 手动检测复选框状态 ExtJS 4.1 中的编程更改

javascript - 将 Ruby 中创建的 JSON 对象漂亮地打印到 Chrome 浏览器控制台

php - Laravel 7 : Why isn't my session cookie getting set in a browser?

php - 查找顶级父级(递归)

javascript - javascript如何将字符串转换为数字数组

php - 在 Iframe 中丢失 SSL

javascript - 如何从contenteditable div中获取从开始到光标位置的文本

javascript - 无法在 Materialize CSS 中更改模式的类名

javascript - AngularJS ng-disabled - 如果输入 $pristine 则不起作用,但如果输入 $pristine 则起作用