这很容易做到,只需XmlHttpRequest
在脚本开头包含这个包装器(它使它更易于使用):
var xhrRequest = function (url, type, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
callback(this.responseText);
};
xhr.open(type, url);
xhr.send();
};
然后这样称呼它:
xhrRequest(url, 'GET', function(responseText) {
console.log("This is the content you got: " + responseText);
});
如果你用 JSON 格式化你的内容,它实际上会让你更容易,因为你不必解析文件,你可以使用 JavaScript 自动为你解析它:
例如,如果回复是:
{ onlineCount: 42, usernames: [ "Alice", "Bob", "Charlie", "etc" ] }
然后你可以像这样处理它:
xhrRequest(url, 'GET',
function(responseText) {
// responseText contains a JSON object
var json = JSON.parse(responseText);
// Now you can process this as a JavaScript dictionary
console.log("Number of online players: " + json.onlineCount);
console.log("First player: " + json.usernames[0]);
// And send messages to Pebble
Pebble.sendAppMessage({ 0: json.onlineCount });
}
);
对于一个完整的示例和 C 端(在 Pebble 上),您应该在 Pebble 教程的第 3 步中获取战利品,它使用天气数据正是这样做的。