douqiao8370 2017-05-31 18:09
浏览 230
已采纳

“php:// input”为json ajax请求返回字符串

I am getting a string from file_get_contents('php://input'). I tried json_decode(), but the string is not a json. Here is the ajax request and the php code. How can I get the json sent from the ajax request and turn it into a php array?

$data = file_get_contents('php://input');
var_dump($data);
echo $data;

Output:

string(7) "id=myId"
"id=myId"

Ajax(Includes Jquery):

$.ajax({
    "url": "myFile.php",
    "type": "POST",
    "contentType": "Json",
    "data": {"id": "myId"},
}).done(function(data, status) {
    if (status == "success") {
        console.log(data);
    }
}).fail(function(data, status, error) {
    throw new Error(error);
    console.log(data);
    console.log(status);
});

Edit: json_encode() is returning null, so I cannot use the answer from this question: PHP: file_get_contents('php://input') returning string for JSON message

  • 写回答

1条回答 默认 最新

  • dousong5492 2017-05-31 18:12
    关注

    Like Sammitch mentioned in his comment, your current code is sending it with form encoding. For what you want, stringify the data before sending it to the server, so that it gets received as JSON. Modify your call to be like this:

    $.ajax({
        "url": "myFile.php",
        "type": "POST",
        "contentType": "application/json",
        "data": JSON.stringify({"id": "myId"}),
    })
    

    This should result in the input being a json encoded object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件