如何从PHP脚本发送JSON数据供jQuery使用

How can I send JSON data from a PHP script to be used by jQuery?

本文关键字:数据 JSON jQuery 使用 PHP 脚本      更新时间:2023-09-26

我对一些JSON数据有问题。我不知道如何将一些用PHP生成的数据转化为可以在jQuery脚本中使用的数据。我需要的功能是:我需要能够点击页面上的图像,并且根据所选的元素,我需要显示我的DB中的结果。

这是我的HTML页面:

<html>
  <head>
  <title>pippo</title>
  <script><!-- Link to the JS snippet below --></script>
  </head>
  <body>
    Contact List:
    <ul>
      <li><a href="#">
        <img src="contacts/pippo.png" onclick="javascript:change('pippo')"/>pippo
      </a></li>
      <li><a href="#">
        <img src="contacts/pluto.png" onclick="javascript:change('pluto')"/>pluto
      </a></li>
      <li><a href="#">
        <img src="contacts/topolino.png" onclick="javascript:change('topolino')"/>topolino
      </a></li>
    </ul>
  </body>
</html>

以下是被调用的PHP代码:

<?php
include('../dll/config.php');
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
    $_POST['name'] = ucfirst($row['name']);
    $_POST['tel'] = $row['telephone'];
    $_POST['companymail'] = $row['companymail'];
    $_POST['mail'] = $row['email'];
    $_POST['fbid'] = $row['facebook'];
}
?>

以下是我正在使用的Ajax JavaScript代码:

<script type="text/javascript">
    function change(user) {
        $.ajax({
            type: "POST",
            url: "chgcontact.php",
            data: "surname="+user+"&name=&tel=&companymail=&mail=&fbid",
            success: function(name,tel,companymail,mail,fbid){
                alert(name);
            }
        });
        return "";
    }
</script>

有人告诉我,这个JS片段可以做我想做的事:

$.getJSON('chgcontact.php', function(user) {
    var items = [name,surname,tel,companymail,email,facebook];
    $.each(user, function(surname) {
        items.push('surname="' + user + "'name='" + name + "'telephone='" + telephone + "'companymail='" + companymail + "'mail='" + mail + "'facebook='" + facebook);
    });
    /*
    $('<ul/>', {
        'class': 'my-new-list',
        html: items.join('')
        }).appendTo('body');
    */
});

但我并不清楚——我不明白我需要如何使用它,也不明白我应该把它包含在代码中的什么地方。

您必须在PHP脚本中创建一个合适的JSON字符串,然后在脚本末尾echo该字符串。

一个简单的例子:

$person = new stdClass;
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )) {
    $person->name = ucfirst($row['name']);
    $person->tel = $row['telephone'];
    $person->companymail = $row['companymail'];
    $person->mail = $row['email'];
    $person->fbid = $row['facebook'];
}
echo json_encode($person);

您的代码有几个问题,我试图通过这里的更正和注释代码来解释:

HTML&JavaScript

<html>
<head><title>pippo</title>
<!-- added link to jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- javascript can go here -->
<script type="text/javascript">
    $.ajax({
        type: "POST",
        url: "chgcontact.php",
            // use javascript object instead of `get` string to represent data
        data: {surname:user, name:'', tel:'', companymail:'', mail:'', fbid:''},
        success: function(data){
                // removed name,tel,companymail,mail,fbid
                alert(JSON.parse(data));
            }
        });
        return "";
    }
</script>
</head>
<body>
Contact List:
<ul>
<!-- removed `javascript` form onclick handler -->
<li><a href="#"><img src="contacts/pippo.png" onclick="change('pippo')"/>pippo</a></li>
<li><a href="#"><img src="contacts/pluto.png" onclick="change('pluto')"/>pluto</a></li>
<li><a href="#"><img src="contacts/topolino.png" onclick="change('topolino')"/>topolino</a></li>
</ul>
</body>
</html>

PHP

<?php
    $surname = $_POST['surname'];
    $result = mysql_query("select * from profile Where surname='$surname'")
    or die(mysql_error());
    while ($row = mysql_fetch_array( $result )){
        // create data object
      $data = new stdClass();
      // add values to data object
        $data->name = ucfirst($row['name']);
        $data->tel = $row['telephone'];
        $data->companymail = $row['companymail'];
        $data->mail = $row['email'];
        $data->fbid = $row['facebook'];
        // send header to ensure correct mime type
        header("content-type: text/json");
        // echo the json encoded data
      echo json_encode($data);
    }
?>

所有的代码都是未经测试的,但您应该能够看到我在每一步都做了什么。祝你好运

进一步阐述Brian Driscoll的回答。您需要使用user.name格式从返回的$.getJSON("blah", function(user){}); 访问name字段

所以。。。

items.push('surname="'+user+"'name='"+user.name+"'telephone='"+user.telephone+"'companymail='"+user.companymail+"'email='"+user.email+"'facebook='"+user.facebook+);

在你创建的这种格式中,它只会推送一个长而难看的字符串,所以你可能想花一些时间让它看起来更好。祝你好运

张贴到PHP页面的JSON通常不在$_POST变量中,而是在$HTTP_RAW_POST_DATA中。