- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是一个简单的普通 JS 脚本,连接到 CoinMarketCap.com ticker API .
它应该做什么:
1) 检索硬币数据,将其存储在对象中
2) 等待 x 时间(在本例中为三分钟)
3) 重复 1),检索更新的数据
4)比较最近的数据和以前的数据
5) 如果硬币的值(value)上涨,console.log
警报
6)重复该过程
它的作用是什么:这两个对象( firstValue
和 secondValue
)是重复的。另外,当重新开始时(再次调用 main()
函数),这两个对象的内容无法更新,并显示以前的值。
// Variables
// Set first recorded value
var firstValue;
// Set second value (most recent)
var secondValue;
// Get the obj from CoinMarketCap API
function getCoinValues() {
var requestURL ="https://api.coinmarketcap.com/v1/ticker/?limit=10";
var request = new XMLHttpRequest();
request.open("GET", requestURL);
request.send();
// When loaded assign to obj variable and return it
request.onload = function getUsdValues() {
// Save data to the 'obj' object
obj = JSON.parse(request.response);
console.log("Retrieved coin data");
};
return obj;
}
// Wait
function wait(ms){
console.log("Waiting.")
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
// Compare two objects
function comparePrices (obj1, obj2) {
// Take price from one array, compare to the other
for (var i = 0; i < obj1.length; i++) {
// console.log(JSON.stringify(obj2[i].id) + " OLD:" + obj1[i].price_usd + "NEW:" + obj2[i].price_usd)
if (obj2[i].price_usd > obj1[i].price_usd) {
console.log(JSON.stringify(obj2[i].id) + " has increased!");
console.log("From $" + obj1[i].price_usd + " to $" + obj2[i].price_usd);
}
}
}
// Main function //
function main () {
// Get 1st coin values
console.log("Getting first values");
firstValue = getCoinValues();
// Wait
console.log("Waiting")
wait(30000);
// Retrieve new values
console.log("Getting second values")
secondValue = getCoinValues();
// Compare two sets of values
console.log("About to compare prices")
comparePrices(firstValue, secondValue);
console.log("Prices compared")
// Do it all again
// "Emptying" the variables
firstValue = null
secondValue = null
// Starting the main loop
main();
}
main();
为什么不firstValue
和secondValue
即使价格在股票行情中有效变化,也会显示不同的结果?
请原谅任何技术术语的不当使用以及整体编码新手。
最佳答案
OP 代码包含许多技术和逻辑错误。请参阅固定代码内的注释。
// Variables
// Set first recorded value
//var firstValue; //no use
// Set second value (most recent)
//var secondValue; //no use
//Save AJAX response here
var currentValue = [];
//define the const URL
var requestURL = "https://api.coinmarketcap.com/v1/ticker/?limit=10";
// Get the obj from CoinMarketCap API - wrong description
//Process request to API
function getCoinValues() {
//var requestURL = "https://api.coinmarketcap.com/v1/ticker/?limit=10";
var request = new XMLHttpRequest();
request.open("GET", requestURL);
//request.send();//dedine a handler first
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) { //**this** is request
var tmpObj = JSON.parse(this.responseText);
if (currentValue && tmpObj) {//compare when both arrays exist
comparePrices(currentValue, tmpObj);
}
if (tmpObj) //response received and parsed
currentValue = tmpObj;
//console.log(tmpObj);
}
}
//now it is good time to send request
request.send();
// When loaded assign to obj variable and return it
//request.onload = function getUsdValues() {
// // Save data to the 'obj' object
// obj = JSON.parse(request.response); //obj was never defined
// console.log("Retrieved coin data");
//};
//return obj; //never try to return anything from asynchronous function
}
// Wait
//Good to hang the system
/*
function wait(ms) {
console.log("Waiting.")
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
*/
// Compare two objects (arrays in fact)
function comparePrices(obj1, obj2) { //usage: comparePrices(current,new)
console.log(new Date().toLocaleTimeString());
// Take price from one array, compare to the other
for (var i = 0; i < obj1.length; i++) {
// console.log(JSON.stringify(obj2[i].id) + " OLD:" + obj1[i].price_usd + "NEW:" + obj2[i].price_usd)
if (obj2[i].price_usd > obj1[i].price_usd) {
//console.log(JSON.stringify(obj2[i].id) + " has increased!"); //no need to stringify.
console.log(obj2[i].id + " has increased! From $" + obj1[i].price_usd + " to $" + obj2[i].price_usd);
} else if (obj2[i].price_usd < obj1[i].price_usd) {
console.log(obj2[i].id + " has decreased! From $" + obj1[i].price_usd + " to $" + obj2[i].price_usd);
} else {
console.log(obj2[i].id + " No change $" + obj2[i].price_usd);
}
}
}
// Main function //
function main() {
getCoinValues();
setTimeout(main, 30000);//run again in 30 sec
return;
//All remaining code is wrong
//// Get 1st coin values
//console.log("Getting first values");
//firstValue = getCoinValues();
//// Wait
//console.log("Waiting")
//wait(30000);
//// Retrieve new values
//console.log("Getting second values")
//secondValue = getCoinValues();
//// Compare two sets of values
//console.log("About to compare prices")
//comparePrices(firstValue, secondValue);
//console.log("Prices compared")
//// Do it all again
//// "Emptying" the variables
//firstValue = null
//secondValue = null
//// Starting the main loop
//main();
}
main();
我本来想创建一个代码片段,但决定不这样做。
关于javascript - Xhr : API Cryptocurrency price alert script returns wrong and duplicate values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46995372/
这可能是一个非常明显的问题,但请解释一下 xhr 和 xhr.upload 之间的区别是什么? 我的用例是我正在将文件上传到服务器,但假设服务器出现故障。在这种情况下,我应该处理 xhr.onerro
这是我的场景: 我有一个 URL,可以生成管理工作区的大量导出 - 它通常约为 3mb,需要约 15 秒才能生成。 当前的实现是对按钮上带有 download 属性的 URL 的正常同步请求,以强制下
我正在执行 XMLHttpRequest,如果失败,我想回退到执行其他操作(读取本地文件),但我想在 XHR 函数 (getDBfileXHR) 本身之外执行此操作。 我也在使用 Jquery。 考虑
XMLHttpRequest 实例上有五个事件。 var xhr = new XMLHttpRequest(); xhr.onloadstart = res => { console.log(
xhr.open('put',url,false) xhr.upload.addEventListener('load',function(e){alert(xhr.responseText)},fa
我正在尝试 promisify the native XHR , 现在问题来了,当我使用下面的代码时: function request(method, url) { return new P
我想知道.. 我怎样才能得到 XHR finished loading 字符串? 基本上,我在 Google instant 的页面上,我想以字符串的形式返回搜索结果的“真实”URL。 最佳答案 如果
是否可以在 XMLHttpRequest 的 onreadystatechange 处理程序中找到作为参数发送到 XMLHttpRequest 的 send(data) 函数的数据?我认为此时它必须存
当我在 xhr.then() 中返回“结果”并且我使用 dojo 1.10.4 时遇到一些问题,请帮助我! 以下代码在dojo中使用xhr('dojo/request/xhr')连接到API: rem
这个问题在这里已经有了答案: How to structure nested Promises (3 个答案) 关闭 6 年前。 我需要做一个 promise 序列。我想使用基于标准的方法(ES6?
当执行“GET”请求时,xhr.response 和 xhr.responseText 都返回相同的值。有什么不同?有吗? 最佳答案 response 被解释为 ArrayBuffer、Blob、Do
我只需要支持主要的现代浏览器(IE10+、FF、Chrome、Safari) 我可以做这个替换吗,因为我想简化我的代码库: 来自: xhr.onreadystatechange = function
DataTables 版本:1.10.20 我目前正在使用 pipeline plugin并聆听 xhr event 。 xhr 事件按预期触发,但是回调中的 xhr 参数未定义。设置对象中还有一个
在非常高的级别上,我们单击一个命令建筑物控制点的按钮;打开或关闭灯。单击应该向服务器发送 POST 请求。问题是有时单击按钮但 POST 请求不会发出。该按钮没有指示它是否已被单击的功能(小幅增强)。
我正在尝试使用 youtube v3 API 上传视频,查看 this示例。 所以,我写了这样的东西: var xhr = new XMLHttpRequest(); xhr.open('PUT',
我正在使用 XHR GET 获取 Blade html 并尝试缓存它,这样它就不需要每次都去服务器下载它。这是我的代码。 但这不起作用并且总是转到服务器。 $.ajax({ method: "
我正在尝试为文件上传创建一个进度条,但由于某种原因,XHR 进度响应仅在最后触发一次。但是,如果我打开 firebug 窗口,它可以 100% 正常工作(在文件上传过程中触发)。我正在本地主机上测试它
我正在尝试获取 xhr 请求。 (该脚本应每 2 秒循环运行一次)这是我的脚本: function getJson() { var xhr = new XMLHttpReque
我有一个简单的 XHR 来加载“testdirectory/testpage.html” var xhr; (XMLHttpRequest) ? xhr= new XMLHttpRequest() :
我正在使用XHR npm 上的 lib 用于在 JS 应用程序的客户端发出 ajax 请求。我的代码如下所示: xhr({uri: "http://foo"},function (err, resp,
我是一名优秀的程序员,十分优秀!