donglu7286 2013-08-13 17:30
浏览 30

将JSON发送到PHP并获得响应

I'm just learning how to use jQuery and PHP together. This is my first attempt, and I feel like I'm almost getting the concept. However, there's an issue I failed to address. When I post a JSON object to PHP script and try to return one of the parameters, I get the following error : "Trying to get property of non-object in ..."

index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-git2.js"></script>
        <meta charset=utf-8 />
        <title>JS Bin</title>
        <style id="jsbin-css"></style>
    </head>
    <body>
        <button onClick="postData();">Submit me!</button>
        <script>
            function postData() {
                var myData = {
                    'firstName' : 'John',
                    'lastName' : 'Doe'
                };   

                $.ajax( {
                    type: "POST",
                    url: "postData.php",
                    contentType: "application/json",
                    data: myData,
                    success: function(msg){ 
                        alert(msg);
                    },
                    error: function(err) {
                         alert('error!' + err);
                    }
                });
            }
        </script>
    </body>
</html>

postData.php:

<?php
    $input = file_get_contents('php://input');
    $jsonData = json_decode($input);    
    $output = $jsonData->{'firstName'};
    echo $output;
?>
  • 写回答

4条回答 默认 最新

  • douzhan3900 2013-08-13 17:34
    关注

    json_decode (depending on PHP version) defaults to returning an array, not an object. The proper way to access it would be:

    $output = $jsonData['firstname'];
    

    You'll also want it to return an associative array, so pass true as the second argument of json_decode.

    $jsonData = json_decode($input, true);  
    

    What could alternately be happening is that the JSON is invalid, in which case PHP returns null. You can check for that:

    if ($jsonData = json_decode($input, true) === null) {
        // Do stuff!
    } else {
        // Invalid JSON :(
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数