2011-11-23 46 views
2

我很新使用jquery和jquery移動,但我想知道是否有一個簡單的方法(或教程優選)將數據庫(遠程和本地)綁定到jQuery的移動網站(最好不要使用PHP)。添加數據庫到jquery移動站點

回答

5

您可以通過JavaScript使用HTML5本地存儲,這裏是一個解釋和一些教程的鏈接:http://www.html5rocks.com/en/features/storage

...現在有多種技術可讓應用程序將數據保存在 客戶端設備.. 。

如果你想與你的服務器交互,那麼你將需要使用服務器端腳本語言。這是相當容易使用AJAX與服務器進行通信:

JS--

//run the following code whenever a new pseudo-page is created 
$(document).delegate('[data-role="page"]', 'pagecreate', function() { 

    //cache this page for later use (inside the AJAX function) 
    var $this = $(this); 

    //make an AJAX call to your PHP script 
    $.getJSON('path_to/server/script.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'); 
    }); 
}); 

PHP--

<?php 

//include your database connection code 
include_once('database-connection.php'); 

//query your MySQL server for whatever information you want 
$query = mysql_query("SELCT * FROM fake_table WHERE fake_col='fake value'", $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)); 
} 
?> 

您也可以將數據發送到你的PHP腳本和將它添加到數據庫中。

下面是用於上述功能的一些文檔頁面:

jQuery的.getJSON()http://api.jquery.com/jquery.getjson

PHP json_encode()http://www.php.net/json_encode

0

使用http://westcoastlogic.com/lawnchair/
它提供存儲的很多方面實際上,你可以把所有的適配器(如何存儲的選項),以便它能夠在瀏覽器中找到第一個。 另外它使用JSON格式,不管你是否想使用localstorage或sqlite,所以你只需要處理JSON數據。

0

如果你想要一個數據庫,手機瀏覽器裏面的SQLLite的普遍支持形式爲Web SQL Databases,目前在大多數android和iPhone設備中都支持。

要看到工作的例子查看以下鏈接:

http://desalasworks.com/html5-databases-on-iphone/

注意,在SQLLite可用的SQL語言是不是比較有限(我認爲是)你的MySQL數據庫。您可以創建/刪除表格,選擇,插入和更新,但某些更高級的操作將會丟失。