【问题标题】:Passing Json using Ajax Post via javascript to php not working使用 Ajax Post 通过 javascript 将 Json 传递给 php 不起作用
【发布时间】:2012-05-12 15:17:45
【问题描述】:

您好,我正在尝试使用 Javascript 通过 Ajax 将 Json 发送到 PHP。当我在萤火虫上查看数据时,index.html 正确发送了数据。它显示具有正确数据的 Json 类型。 但是,似乎我无法读取 php 上的 JSON。我无法使用 $_POST 访问它。 我尝试使用 $_POST['name'] 并且没有响应。 当我尝试使用 $_POST 时,响应是数组。 你能帮帮我吗?

这是我的 javascript 代码。

<html>
<head>
<script type="text/javascript">
    //Create Http request depending on browser
    var xmlhttp;
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();}
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

    xmlhttp.onreadystatechange=function(){
      if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;}
      }

    // Function to create 
    var url = "control.php";
    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    var data=JSON.stringify({"name":"John", "time":"2pm"});
    xmlhttp.send(data);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>

这是我的 php 代码

<?php
include_once('JSON.php');   
$json = new Services_JSON();
$value = $json->decode($_POST['name']);
echo $value;
?>

已经为此工作了几天,我非常感谢您提供的任何帮助。 谢谢!

【问题讨论】:

  • 为什么不使用 javascript 库?
  • 使用 jQuery.ajax();如果您遇到请求问题,请使用 Firefox(选项卡控制台或网络)的 Firebug 插件进行调查
  • 执行 print_r($_POST) 你会看到你的 $_POST 全局变量是什么。也许它会帮助你解决问题

标签: php javascript ajax json post


【解决方案1】:

一个更好的解决方案(参见here)是使用:

$json = json_decode(file_get_contents("php://input"), true) ?: [];
print_r($json);

【讨论】:

    【解决方案2】:

    我认为它需要先解析整个帖子。

    <?php
    include_once('JSON.php');   
    $json = new Services_JSON();
    $value = $json->decode($_POST);
    echo $value;
    ?>
    

    但您还需要这些包含吗? http://www.php.net/manual/en/function.json-decode.php

    include_once('JSON.php');   
    $json = new Services_JSON();
    

    你不能只做这个吗?

    echo json_decode($_POST)
    

    【讨论】:

    • 您好,感谢所有 cmets 和答案!我尝试按照您的建议仅使用 echo json_decode($_POST) ,但给出的响应为空白。当我尝试执行 print_r($_POST) 时,给定的输出是 ararray()。
    【解决方案3】:

    这里是:

    print_r($GLOBALS['HTTP_RAW_POST_DATA']);
    

    【讨论】:

    • 嘿!非常感谢!这为我解决了这个问题。你能指出我可以阅读为什么 $GLOBALS['HTTP_RAW_POST_DATA'] 在这种情况下工作的文档吗?不过还是非常感谢各位!你让我很开心=)
    • 你可以在这里找到它PHP Manual。但是当我遇到这样的问题时,我会做一些测试,比如(print_r($GLOBAL),print_r($_SERVER))。这很有帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 2013-07-25
    • 2015-10-30
    • 1970-01-01
    • 2015-04-01
    • 2019-08-28
    • 2013-03-05
    • 1970-01-01
    • 2014-04-30
    相关资源
    最近更新 更多