繁体   English   中英

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

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

我对某些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');
    */
});

但是我不清楚-我不知道该如何使用它或在代码中的什么位置添加它。

您将必须在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字段$.getJSON("blah", function(user){});

所以...

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

以您创建的这种格式,它只会插入看起来很长的丑陋字符串,因此您可能要花一些时间使它看起来更好。 祝好运!

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

暂无
暂无

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

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