2013-03-17 46 views
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和下面是PHPjsoncallback位于哪里?上述

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

+0

你是使用[一个**过时的**数据库API](http://stackoverflow.com/q/12859942/19068),并应使用[现代替换](http://php.net/manual/en/mysqlinfo.api .choosing.php)。你也**易受[SQL注入攻击](http://bobby-tables.com/)**,现代的API会使[防御]更容易(http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)自己从。 – Quentin 2013-03-17 23:06:14

+0

JSON-P的正确内容类型是'application/javascript',JSON-P是一个JavaScript函数调用,而不是数据格式。 – Quentin 2013-03-17 23:06:55

+0

我很困惑你在问什么。试图''jsoncallback'到'displayStudent'? – VeXii 2013-03-17 23:33:19

回答

0

callback函数应采取三个参数:

数据,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,我觉得(我没有使用PHP 12年...),只是需要:

<?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); 
?> 
+0

在我以前的问题中,由于一些跨域问题,我想添加jsoncallback来修复它。所以我想知道应该删除它吗? http://stackoverflow.com/questions/15463296/how-to-display-json-content-in-li-format-in-phonegap – HUNG 2013-03-17 23:13:34