2013-03-17 80 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