【问题标题】:Cannot get data in PHP from JQuery Ajax post with JSON无法从带有 JSON 的 JQuery Ajax 帖子中获取 PHP 中的数据
【发布时间】:2025-12-08 17:15:01
【问题描述】:

我正在尝试一个简单的测试来了解 JQuery Ajax POST 方法,并且我在我的服务器上设置了一个小示例。但是我不能让它工作。

我的 JavaScript 如下:

JavaScript:

var json = {"Num String":"2","Num":3,"Num":11,"Num":2,"Num":"?"};
$.ajax({
        type: "POST",
        url: "sampleJSONPost.php",
        data: json, //Data to POST to the server
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (jqXHR, status, err) {
            console.log("Error " + err + " " + status + " " + JSON.stringify(jqXHR)); //Log the Error 
        },
        success: function (data, status, jqXHR) {  
              console.log(JSON.stringify(data)); //Log the Data returned
              $("span").text(data);
        }
    });
};

这是我的 PHP:

PHP:

<?php
$data = $_POST["data"];
echo json_decode($data);
?>

但是这总是给我以下错误:

Error SyntaxError: Unexpected end of input parsererror {"readyState":4,"responseText":"","status":200,"statusText":"OK"} 

所以对我来说,我在 PHP 中的 $data 变量似乎没有收到我通过 POST 发送的 JSON,这是正确的吗?如果是这样,谁能帮我找出问题所在?我已经尝试过 SO 的许多其他解决方案,但都没有成功,所以我一定缺少一些简单的东西吗?

【问题讨论】:

    标签: javascript php jquery json http-post


    【解决方案1】:

    换成

    var json = {"data":{"Num String":"2","Num":3,"Num":11,"Num":2,"Num":"?"}};
    

    【讨论】:

    • 或者在服务器端 $data = $_POST;
    • 从你的 ajax 配置中移除 dataType: "json" 行
    • 和 contentType: "application/json; charset=utf-8", 还有
    【解决方案2】:

    改变

          data: json,
    

        data: JSON.stringify({ json : json }),
    

    【讨论】:

      【解决方案3】:

      试试这个

      var json = {{"Num String":"2"},{"Num":3},{"Num":11},{"Num":2}};
      

      这个,我不检查

      $.ajax({
          type: 'POST',
          url: 'sampleJSONPost.php',
          contentType: 'application/json; charset=utf-8',
          data: { "Num String":"2","Num":3,"Num":11,"Num":2,"Num":"?" },
          dataType: 'json',
          success: function(data)
      {
      
      },
          error: AjaxFailed
      });
      

      【讨论】:

        最近更新 更多