jsoncallback应该在哪里?

时间:2013-03-17 23:03:16

标签: php javascript json cordova

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值是否被错误地实现。你的意见将是一个很大的帮助。感谢

1 个答案:

答案 0 :(得分:0)

回调函数应该有三个参数:

data,textStatus,jqXHR

数据是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);
?>