我正在尝试从我控制的服务器加载一个非常简单的文本文件(例如: 0 online:
或 1 online: Username
或 2 online: Username, Username
),该文件根据我的世界服务器上的用户数量而变化,到一个 javascript var,这样我最终可以将它加载到我的 Pebble 上并或多或少地进行实时更新。 (阅读:没有jquery)(另请阅读:我几乎不知道我实际上在做什么,如果有更好的方法,请让我知道。)。
我已经做了lot of googling这主要指向 using JSON and XMLHTTPRequests (编辑:XMLHTTPRequests 可能是必要的)但它们对于我所需要的东西来说似乎过于复杂(即获取通过 HTTP 提供的文本文件的内容,将其填充到 var 中,然后让 Pebble 将其吐出到屏幕上。 )
在没有 JQuery 甚至没有 JSON 的情况下,如何将文本文件的内容加载到 javascript var 中?
一些注意事项:
- 服务器最终将通过 Hamachi 进行访问,但如果我什至可以在本地让它工作,我会非常兴奋。
- 正在关注this answer ,我得到this result 。本地 IP 也是如此。
最佳答案
这很容易做到,只需包含 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 上),您应该在 Step 3 of the Pebble Tutorial 获取战利品,它正是利用天气数据来实现这一点。
关于javascript - 如何将小文本文件的内容加载到 javascript var wo/JQuery 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27840222/