我正在開發一個將極大地依賴遠程數據庫的使用的Android應用程序的團隊。我們正在使用PhoneGap和Jquery Mobile,並試圖使用AJAX和JSON調用連接到我們的MySQL數據庫。目前,我們在測試階段遇到問題,即通過MySQL Workbench從mySQL /輸入中拉取「Ted」的硬編碼用戶來驗證我們甚至有連接。使用PhoneGap,AJAX和JQuery Mobile連接到MySQL數據庫
從我們已經收集,數據傳輸過程中的工作,因爲這:
在我們的HTML文件,我們有一個
<script type="text/javascript" src="Connect.js"></script>
^這應該運行Connect.js腳本,對嗎?那麼從那裏,Connect.js運行?
Connect.js會運行,將它連接到託管在外部Web服務上的ServerFile.php,從而允許它運行PHP以連接到MySQL數據庫並獲取信息。
//run the following code whenever a new pseudo-page is created $('#PAGENAME').live('pageshow', function(event)) { // cache this page for later use (inside the AJAX function) var $this = $(this); // make an AJAX call to your PHP script $.getJSON('http://www.WEBSITENAME.com/ServerFile.php', function (response) { // create a variable to hold the parsed output from the server var output = []; // if the PHP script returned a success if (response.status == 'success') { // iterate through the response rows for (var key in response.items) { // add each response row to the output variable output.push('<li>' + response.items[key] + '</li>'); } // if the PHP script returned an error } else { // output an error message output.push('<li>No Data Found</li>'); } // append the output to the `data-role="content"` div on this page as a // listview and trigger the `create` event on its parent to style the // listview $this.children('[data-role="content"]').append('<ul data-role="listview">' + output.join('') + '</ul>').trigger('create'); }); });
這裏是ServerFile.php。這應該連接到MySQL數據庫,製作Select語句,然後將輸出發送到以JSON格式編碼的瀏覽器。
<?php
//session_start();
$connection = mysql_connect("csmadison.dhcp.bsu.edu", "clbavender", "changeme");
$db = mysql_select_db("cs397_clbavender", $connection);
//include your database connection code
// include_once('database-connection.php');
//query your MySQL server for whatever information you want
$query = mysql_query("SELECT * FROM Users WHERE Username ='Ted'", $db) or trigger_error(mysql_error());
//create an output array
$output = array();
//if the MySQL query returned any results
if (mysql_affected_rows() > 0) {
//iterate through the results of your query
while ($row = mysql_fetch_assoc($query)) {
//add the results of your query to the output variable
$output[] = $row;
}
//send your output to the browser encoded in the JSON format
echo json_encode(array('status' => 'success', 'items' => $output));
} else {
//if no records were found in the database then output an error message encoded in the JSON format
echo json_encode(array('status' => 'error', 'items' => $output));
}
?>
然而這裏沒有任何東西顯示。我們在這裏做什麼?
您是否已經完成了任何調試以確定代碼中的問題所在?我建議把'echo json_encode(array('status'=>'success'));退出;'在ServerFile.php的開始處查看是否問題在於它在SQL的某個位置被阻塞,或者如果它在讀取返回的內容時遇到問題。 –
或者,另一種調試方式是將'console.log(response);'放在$ .getJSON函數中。這個響應會出現在你的Firebug中。 –