【发布时间】:2011-08-10 03:50:43
【问题描述】:
我已经使用webOS Ares 工具创建了一个相对简单的App。它显示一个图像,图像下方是两个标签。一个是静态的,另一个标签应该通过点击图像来更新新信息。
当我点击图片时,我希望通过 URL (http://jonathanstark.com/card/api/latest) 获取 JSON 对象。返回的典型 JSON 如下所示:
{"balance":{"amount":"0","amount_formatted":"$0.00","balance_id":"28087","created_at":"2011-08-09T12:17:02-0700","message":"My balance is $0.00 as of Aug 9th at 3:17pm EDT (America\/New_York)"}}
我想解析 JSON 的“amount_formatted”字段并将结果分配给动态标签(在 main-chrome.js 中称为 cardBalance)。我知道 JSON 应该根据 API 返回一个对象。
如果一切顺利,我将创建一个附加标签并将“created_at”字段转换/分配为附加标签,但我想在跑步之前先步行。
我在使用 AJAX 获取 JSON、解析 JSON 并将字符串分配给其中一个标签时遇到了一些问题。
在我完成这项工作后,我打算看看我是否可以在应用程序的负载上加载这个结果,而不是首先要求用户点击。
到目前为止,这是我在 main-assistant.js 文件中的代码。 jCard 是图像。 代码:
function MainAssistant(argFromPusher) {}
MainAssistant.prototype = {
setup: function() {
Ares.setupSceneAssistant(this);
},
cleanup: function() {
Ares.cleanupSceneAssistant(this);
},
giveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
},
jcardImageTap: function(inSender, event) {
//get "amount_formatted" in JSON from http://jonathanstark.com/card/api/latest
//and assign it to the "updatedBalance" label.
// I need to use Ajax.Request here.
Mojo.Log.info("Requesting latest card balance from Jonathan's Card");
var balanceRequest = new Ajax.Request("http://jonathanstark.com/card/api/latest", {
method: 'get',
evalJSON: 'false',
onSuccess: this.balanceRequestSuccess.bind(this),
onFailure: this.balanceRequestFailure.bind(this)
});
//After I can get the balance working, also get "created_at", parse it, and reformat it in the local time prefs.
},
//Test
balanceRequestSuccess: function(balanceResponse) {
//Chrome says that the page is returning X-JSON.
balanceJSON = balanceResponse.headerJSON;
var balanceAmtFromWeb = balanceJSON.getElementsByTagName("amount_formatted");
Mojo.Log.info(balanceAmtFromWeb[0]);
//The label I wish to update is named "updatedBalance" in main-chrome.js
updatedBalance.label = balanceAmtFromWeb[0];
},
balanceRequestFailure: function(balanceResponse) {
Mojo.Log.info("Failed to get the card balance: " + balanceResponse.getAllHeaders());
Mojo.Log.info(balanceResponse.responseText);
Mojo.Controller.errorDialog("Failed to load the latest card balance.");
},
//End test
btnGiveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
}
};
这是在 Chrome 浏览器中运行的应用程序的屏幕截图:
在浏览器中,我收到了一些在 Ares 日志查看器中不存在的其他错误:
XMLHttpRequest cannot load http://jonathanstark.com/card/api/latest. Origin https://ares.palm.com is not allowed by Access-Control-Allow-Origin.
和
Refused to get unsafe header "X-JSON"
感谢任何帮助。
【问题讨论】:
标签: javascript json webos