繁体   English   中英

发送JSON到PHP并获得响应

[英]Send JSON to PHP and get a response

我正在学习如何一起使用jQuery和PHP。 这是我的第一次尝试,我觉得自己快要明白了。 但是,我没有解决一个问题。 当我向PHP脚本发布JSON对象并尝试返回参数之一时,出现以下错误:“试图在...中获取非对象的属性”

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;
?>

通过更多的工作,您可以使用REST客户端实现此目的,该客户端将自动处理数据类型转换和URL解析等操作。

列举使用REST体系结构的一些优点:

  • 简单。

  • 您可以使用缓存,负载平衡等轻松扩展解决方案。

  • 允许您在逻辑上分隔URL端点。

  • 它使您可以灵活地轻松更改实施而无需更改客户端。

尝试阅读REST简介,以更好地了解设计模式及其用途。 当然,如果您不想的话,也不需要从头开始编写框架,因为那里已经有一些基于PHP的开源实现,例如Recess PHP Rest Framework

希望这可以帮助!

json_decode (取决于PHP版本)默认为返回数组,而不是对象。 访问它的正确方法是:

$output = $jsonData['firstname'];

您还希望它返回一个关联数组,因此将true作为json_decode的第二个参数传递。

$jsonData = json_decode($input, true);  

另一种可能是JSON无效,在这种情况下,PHP返回null 您可以检查一下:

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

我用jquery的函数发布将它简化了一点。 希望你觉得它有用:

首先你的HTML和JS:

<!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() {
        $.post(
            "postData.php",
            {
                firstName : 'John',
                lastName : 'Doe'
            },
            function(msg)
            {
                alert(msg);
            }
        );
      }

      </script>
      </body>
      </html>

然后你的PHP:

<?php
    echo $_REQUEST['firstName']." - ".$_REQUEST['lastName'];
?>

我终于想通了:

js:

function postData() {
var myData = {
  firstName: 'John',
  lastName: 'Doe'
};     

$.ajax({
    type: "POST",
    url: "postData.php",
    data: JSON.stringify(myData),
    success: function(msg){ 
        alert(msg);
    },
    error: function(err){
      alert('error!' + JSON.stringify(err));
    }
});
}

的PHP:

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

解码时,您不想将“ true”作为第二个参数,因为那样的话,它不是JSON而是关联数组(或者我已经读过)。 如果我放入json_decode($ input,true),那么它将无法正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM