javascript 使用 PhoneGap、AJAX 和 JQuery Mobile 连接到 MySQL 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15696440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:45:42  来源:igfitidea点击:

Connecting to a MySQL database using PhoneGap, AJAX, and JQuery Mobile

javascriptjquerysqlcordovajquery-mobile

提问by Spookytheboy

I'm in a team developing an Android application that will rely greatly on the use of a remote database. We are using PhoneGap and Jquery Mobile and have been attempting to connect to our MySQL database using AJAX and JSON calls. Currently, we are having trouble in our testing phase, which is to verify we even have a connection at all by pulling a hard-coded user of "Ted" from mySQL / input via MySQL Workbench.

我在一个开发 Android 应用程序的团队中,该应用程序在很大程度上依赖于远程数据库的使用。我们正在使用 PhoneGap 和 Jquery Mobile,并且一直在尝试使用 AJAX 和 JSON 调用连接到我们的 MySQL 数据库。目前,我们在测试阶段遇到了麻烦,即通过 MySQL Workbench 从 mySQL / 输入中提取“Ted”的硬编码用户来验证我们甚至是否有连接。

From what we have gathered, the process of data transmission works as this:

从我们收集到的信息来看,数据传输的过程是这样的:

  1. On our html file, we have a

    <script type="text/javascript" src="Connect.js"></script>
    

    ^ Which should run the Connect.js script, correct? So from there, Connect.js is ran?

  2. Connect.js runs, connecting it to our ServerFile.php that is hosted on an external web service, allowing it to run PHP to connect to the MySQL database and pull information.

    //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');
        });
    });
    
  1. 在我们的 html 文件中,我们有一个

    <script type="text/javascript" src="Connect.js"></script>
    

    ^ 哪个应该运行 Connect.js 脚本,对吗?那么从那里开始运行 Connect.js?

  2. 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');
        });
    });
    

Here is ServerFile.php. This should connect to the MySQL Database, make the Select statement, and then send the output to the browser encoded in the JSON format.

这是 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));
}
?>

Yet nothing is showing here. What do we do from here?

然而这里什么也没有显示。我们从这里做什么?

回答by wmfairuz

First thing first. Try to determine where is the problem come from, server side or client side.

先说第一件事。尝试确定问题来自哪里,服务器端还是客户端。

Print out your database query and encoded json can be useful. If you are creating a simple API service, you should be able to enter http://www.WEBSITENAME.com/ServerFile.phpusing your browser and look how the output is.

打印出您的数据库查询和编码的 json 可能很有用。如果您正在创建一个简单的 API 服务,您应该能够使用浏览器输入http://www.WEBSITENAME.com/ServerFile.php并查看输出如何。

Use echo to print things with php.

使用 echo 用 php 打印东西。

If all looks ok, time to print out the response you receive from the server in the javascript and see what is off.

如果一切正常,是时候在 javascript 中打印出您从服务器收到的响应,看看有什么问题。

Use console.log to print thing with javascript. The logs should appear in the logcat section of eclipse (since you are developing android app)

使用 console.log 用 javascript 打印东西。日志应该出现在 eclipse 的 logcat 部分(因为您正在开发 android 应用程序)