Google 为 API 端点提供的 client.js 库只能从浏览器(在本例中为 Titanium.UI.WebView)运行,它不能直接从 Titanium 代码运行,因为它包含 Titanium 中不可用的对象加速器。
此外,在 Alloy Titanium 应用程序中使用 Google Cloud Endpoint 需要在编译时将 js 代码提供给项目,因为 Titanium 使用它来为所需平台生成本机代码。
回答您的问题:
-
有没有办法,我可以包含这个文件?
- 不,如果您打算将代码作为 Titanium 代码运行,出于上述原因。相反,您可以使用以下代码 sn-p 连接到 Google Cloud Endpoint:
var url = "@987654321@";
var methodName = "testendpoint.listGreetings";
var apiVersion = "v1";
callMethod(url, methodName, apiVersion, {
success : function(responseText)
{
//work with the response
},
error : function(e) { //onerror do something
}
});
function callMethod(url, methodName, apiVersion, callbacks) {
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
Ti.API.info("received text: " + this.responseText);
if (typeof callbacks.success === 'function') {
callbacks.success(this.responseText);
}
};
xhr.onerror = function(e) {
Ti.API.info(JSON.stringify(e));
//Ti.API.info(e.responseText);
if (typeof callbacks.error === 'function') {
callbacks.error(e);
}
};
xhr.timeout = 5000; /* in milliseconds */
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json-rpc');
//xhr.setRequestHeader('Authorization', 'Bearer ' + token);
var d = [{
jsonrpc: '2.0',
method: methodName,
id: 1,
apiVersion: apiVersion,
}];
Ti.API.info(JSON.stringify(d));
// Send the request.
xhr.send(JSON.stringify(d));
}
- 是的,如果您像这样使用嵌入式设备的浏览器(可以在 Web 客户端 GAE 示例中找到)
webview = Titanium.UI.createWebView({
width : '100%',
height : '100%',
url : url // put your link to the HTML page
});
, 调用您的服务器 HTML 页面,该页面应包含:
script src="https://apis.google.com/js/client.js?onload=init">
有没有办法,我可以创建全局变量?
是的,将全局变量插入到 app/alloy.js 文件中,请参阅文件中的默认 cmets:
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the Alloy.Globals
// object. For example:
//
Alloy.Globals.someGlobalFunction = function(){};
Alloy.Globals.someGlobalVariable = "80dp";
我想您正在引用包含用于连接到 GAE enpoind 方法的模块代码的全局变量。这是你的电话,这是你如何使用它们。
a) 在你的 Titanium 项目的 app/lib 文件夹中创建一个名为 jsonrpc.js 的文件,将以下代码放入其中,并将函数代码从上面移动为函数体:
JSONRPCClient = function () {
};
JSONRPCClient.prototype = {
callMethod : function (url, methodName, apiVersion, callbacks) {
// insert the function body here
}
};
exports.JSONRPCClient = JSONRPCClient;
b) 在 app/alloy.js 文件中定义你的全局变量:
Alloy.Globals.JSONRPCClient = require('jsonrpc').JSONRPCClient;
c) 使用它(例如,从您的控制器 js 文件中):
var client = new Alloy.Globals.JSONRPCClient();
var url = "https://1-dot-projectid.appspot.com/_ah/api/rpc";
var methodName = "testendpoint.listGreetings";
var apiVersion = "v1";
client.callMethod(url, methodName, apiVersion,
{success: function(result) {
//result handling
Ti.API.info('response result=', JSON.stringify(result));
//alert(JSON.stringify(result));
},
error: function(err) {
Ti.API.info('response out err=', JSON.stringify(err));
//error handling
}
});