【问题标题】:Using javascript to get php/mysql values使用 javascript 获取 php/mysql 值
【发布时间】:2011-10-27 09:13:21
【问题描述】:

我正在考虑在 appcellerators 钛应用程序中构建一个 android 应用程序,我有一个问题,该应用程序所针对的网站是使用 php/mysql 构建的,我想知道的是,钛使用 javascript、html 工作并且只有 css,有没有办法我可以使用 javascript 从我的数据库中动态提取数据?

如果这已经发布了,对不起,我搜索并找不到它:S

【问题讨论】:

  • 直接通过 JS - 没有。但是,没有什么能阻止您创建一个与您的 JS 代码对话的服务(使用 PHP 从 MySQL 接收 JSON 格式的数据),这使您能够继续使用钛。

标签: php javascript android mysql titanium


【解决方案1】:

使用 PHP,获取您的数据库响应数组并像这样对其进行编码:

<?php
json_encode($db_array);
?>

更多信息: http://php.net/manual/en/function.json-encode.php

请注意,您需要 PHP 5.2 或更高版本才能拥有 PHP 的内置 JSON 函数。

在 Titanium 中,您想打开一个 XHR(或网络处理程序)来获取数据:

var xhr = Ti.Network.createHTTPClient();
var.onload = function()
{
   try
   {
      data = JSON.parse(this.responseText);
   }
   catch (excp)
   {
      alert('JSON parse failed');
   }

   // you should handle your network async, meaning you should handle any renders or any post elements here. if you make it sync, you'll cause all other handlers and functions to work improperly (like click events, etc).
}

xhr.open("GET", "your url here");
xhr.send();

您可以通过简单地调用 data[0].some_col 来访问数据数组;

【讨论】:

    【解决方案2】:

    尝试阅读有关在 Titanium 应用程序中使用 SQLite 数据库的教程
    对不起,它是 iPhone 的,但基本原理是一样的

    http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite/
    http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-part-2/
    http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-%E2%80%93-part-3/

    使用是这样的:

    var db = Ti.Database.install('../products.sqlite','products');  
    var rows = db.execute('SELECT DISTINCT category FROM products');
    

    文档:
    http://developer.appcelerator.com/apidoc/mobile/1.3/Titanium.Database-module

    【讨论】:

      【解决方案3】:

      如果您从网站访问数据库,最好的方法是使用 json_encode 使用 JSON。如果您尝试使用本地数据库,请使用 sqlite。

      【讨论】:

        【解决方案4】:

        你需要在你的网站上建立一个webservice,并用Titanium.Network.HTTPClient拉取数据

        你可以在这里看到它:http://developer.appcelerator.com/apidoc/mobile/latest/Titanium.Network.HTTPClient-object

        一个例子是:

        var xhr = Titanium.Network.createHTTPClient();
        
        xhr.onload = function() {
            var data = this.responseText; //response is here
            // do your thing within this scope, or call a function/event from here
        }
        
        var url = 'http://www.google.nl';
        xhr.open("GET", url); // or "POST"
        xhr.send();
        

        请注意,数据变量在范围之外是不可访问的,即使它是一个全局变量。从范围内调用您的函数

        在应用程序中,您可以使用 SQLite,也可以不存储数据。最适合您的应用程序的方法

        【讨论】:

          猜你喜欢
          • 2013-07-02
          • 1970-01-01
          • 1970-01-01
          • 2017-07-07
          • 1970-01-01
          • 2014-02-15
          • 1970-01-01
          • 1970-01-01
          • 2015-11-01
          相关资源
          最近更新 更多