繁体   English   中英

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

[英]Undefined index in post method of JSON object sent by jQuery AJAX

我尝试了几乎所有建议,但没有用。 当我使用arr['id'] alert数组时,我的id在JavaScript函数中正常工作。 但是,当我在另一个PHP文件上尝试$_POST['id']时(我使用AJAX并指定了URL)会给我一个错误。

scriptfile.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");
        }
    });
}

detailsmodal.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"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM