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

时间:2012-02-07 19:23:13

标签: php javascript ajax json

我遇到了一些JSON数据的问题。我不知道如何获取PHP中生成的一些数据,并将其转换为我可以在我的jQuery脚本中使用的东西。我需要的功能是:我需要能够点击页面上的图像,并根据所选元素,我需要显示我的数据库的结果。

这是我得到的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');
    */
});

但我不清楚 - 我不明白我需要如何使用它或我应该将它包含在我的代码中。

4 个答案:

答案 0 :(得分:2)

您必须在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);

答案 1 :(得分:2)

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

HTML&amp;的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);

    }

?>

所有代码都未经过测试,但您应该能够看到我在每一步中所做的工作。祝你好运。

答案 2 :(得分:2)

扩展Brian Driscoll的答案。您需要使用user.name格式访问返回的name

中的$.getJSON("blah", function(user){});字段

所以...

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

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

答案 3 :(得分:0)

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