0
function start(){

$('#detailsPage').live('pageshow', function(event) {
    var user_name = getUrlVars()["user_name"];
    //var user_name = "studentB";
    $.getJSON('http://mydomain.com/getStudent.php?user_name='+user_name+'&jsoncallback=?', displayStudent);
});
}

上面是js,下面是php

<?php 

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Content-type: application/json");

include('mysqlConfig.php');

$user_name = $_GET["user_name"];

$sql="SELECT * FROM tbl_user WHERE user_name='$user_name'";
$result=mysql_query($sql);


$rows = array();

//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
    // $rows[] = $r; has the same effect, without the superfluous data attribute
    $rows[] = array('data' => $r);
}

// now all the rows have been fetched, it can be encoded
//echo json_encode($rows);

$data = json_encode($rows);
echo $_GET['jsoncallback'] . '(' . $data . ');';
?>

我想知道这种方法是否有效?在我的应用程序中,第 n 个是显示。我不确定 jsoncallback 值是否被错误地实现。您的意见将有很大帮助。谢谢

4

1 回答 1

0

回调函数应采用三个参数:

数据,文本状态,jqXHR

其中 data 是 php 页面返回的内容。

所以你的JS应该是:

function start(){

    $('#detailsPage').live('pageshow', function(event) {
        var user_name = getUrlVars()["user_name"];
        //var user_name = "studentB";
        $.getJSON('http://mydomain.com/getStudent.php?user_name='+user_name, displayStudent);
    });
}

function displayStudent (data, textStatus, jqXHR) {
    // data will be the json encoded $rows data from your php file 
    // ... do stuff here
}

你 PHP,我想(我已经有 12 年没用过 PHP 了……),只需要:

<?php 

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");    
header("Content-type: application/json");

include('mysqlConfig.php');

$user_name = $_GET["user_name"];

$sql="SELECT * FROM tbl_user WHERE user_name='$user_name'";
$result=mysql_query($sql);


$rows = array();

//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
    // $rows[] = $r; has the same effect, without the superfluous data attribute
    $rows[] = array('data' => $r);
}

// now all the rows have been fetched, it can be encoded

echo json_encode($rows);
?>
于 2013-03-17T23:08:52.310 回答