将数据库添加到jquery移动站点

use*_*411 2 php database jquery local-storage jquery-mobile

我很擅长使用jquery和jquery mobile,但我想知道是否有一种简单的方法(或者教程最好)将数据库(远程和本地)绑定到jquery移动站点(最好不使用php).

Jas*_*per 5

您可以通过JavaScript使用HTML5 localStorage,这里有一个解释和教程的一些链接: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');
    });
});
Run Code Online (Sandbox Code Playgroud)

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));
}
?>
Run Code Online (Sandbox Code Playgroud)

您还可以将数据发送到PHP脚本并将其添加到数据库中.

以下是上面使用的函数的一些文档页面:

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

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