php - 通过 JQuery ajax.post 向 PHP 提交 JSON 数据

标签 php jquery ajax json

我使用 POST 通过 AJAX 将数据提交到 php 文件。 仅提交字符串就可以正常工作,但现在我想使用 JSON 提交 JS 对象并在 PHP 端对其进行解码。

在控制台中我可以看到,我的数据已正确提交,但在 PHP 端 json_decode 返回 NULL。

我尝试过以下方法:

this.getAbsence = function()
{
    alert(JSON.stringify(this));
    jQuery.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ajax/selectSingle.php?m=getAbsence",
        data: JSON.stringify(this),
        success : function(data){
            alert(data);
        }
    });
}

PHP:

echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));

还有:

this.getAbsence = function()
{
    alert(JSON.stringify(this));
    jQuery.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ajax/selectSingle.php?m=getAbsence",
        data: {'Absence' : JSON.stringify(this)},
        success : function(data){
            alert(data);
        }
    });
}

PHP:

echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));

警报只是为了检查一切是否正常......

是的,通常的字符串已正确回显:-)

最佳答案

第一个代码中你的代码出错的地方是你必须使用这个:

var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']

引用自PHP手册

php://input is a read-only stream that allows you to read raw data from the request body.

由于在您的情况下,您在正文中提交 JSON,因此您必须从此流中读取它。 $_POST['field_name'] 的常用方法不起作用,因为帖子正文不是 URL 编码格式。

在第二部分中,你一定使用过这个:

contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),

更新:

当请求的内容类型为 application/json 时,PHP 不会解析该请求并在 $_POST 中为您提供 JSON 对象,您必须自己从原始数据中解析它HTTP 正文。使用 file_get_contents("php://input"); 检索 JSON 字符串。

如果您必须使用$_POST获得它,您会做到:

data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},

然后在 PHP 中执行:

$json = json_decode($_POST['data']);

关于php - 通过 JQuery ajax.post 向 PHP 提交 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31466642/

相关文章:

php - 如何在不使用提交按钮的情况下提交表单

php - php html dom解析器问题中的样式内联样式

javascript - 链式选择框(国家、州、城市)

javascript - 如何在一行中显示多行文本

jquery - 使用 Play 框架处理文件

.net - 通过 jQuery.ajax 将文件夹路径字符串传递给 Web 服务函数时出现问题

php - 如何对 mysql 结果进行编号

php - 删除双向友谊的查询(mysql)

jquery - jqGrid 具有自定义单元格颜色

javascript - 无法执行对 C# 方法的 Ajax 调用