收到响应没有任何问题,但是在接收数据响应后必须更改的属性未定义。可能他们从临时变量获取的值太快了。如何解决这个问题? 顺便说一句,是否有一个选项可以避免那些临时变量并使用if语句中的对象属性?它会好得多。尝试了不同的方式,但它没有工作=(
var tickerBittrex = function(tickerName)
{
this.tickerName = tickerName;
this.requestURL = "https://bittrex.com/api/v1.1/public/getticker?market=" + tickerName;
/* Properties */
this.success = false;
this.message = "";
this.Last = 0;
this.sendRequest = function()
{ /* temp variables */
var success;
var message;
var Last;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(success, message, Last)
{
if (this.readyState == 4 && this.status == 200)
{
console.log(xhttp.responseText); // test
var response = JSON.parse(xhttp.responseText); // parsed response
console.log(response); // test
success = response.success;
message = response.message;
Last = response.result.Last;
console.log(Last); // test
console.log("xhttp.status: " + xhttp.status + " readyStat:" + xhttp.readyStat); // test
}
};
xhttp.open("GET", this.requestURL, true);
xhttp.send();
this.success = success;
this.message = message;
this.Last = Last;
}
}
var bittrexBTC = new tickerBittrex("usdt-btc");
bittrexBTC.sendRequest();
答案 0 :(得分:1)
这应该有效:
var tickerBittrex = function(tickerName) {
this.tickerName = tickerName;
this.requestURL = "https://bittrex.com/api/v1.1/public/getticker?market=" + tickerName;
/* Properties */
this.success = false;
this.message = "";
this.Last = 0;
var self = this;
this.sendRequest = function() { /* temp variables */
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(success, message, Last) {
var success;
var message;
var Last;
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText); // test
var response = JSON.parse(xhttp.responseText); // parsed response
console.log(response); // test
success = response.success;
message = response.message;
Last = response.result.Last;
console.log(Last, success, message); // test
self.success = success;
self.message = message;
self.Last = Last;
console.log(self);
console.log("xhttp.status: " + xhttp.status + " readyState:" + xhttp.readyState); // test
}
};
xhttp.open("GET", this.requestURL, true);
xhttp.send();
}
}
var bittrexBTC = new tickerBittrex("usdt-btc");
bittrexBTC.sendRequest();
说明:
首先,将下面的代码放在onreadystatechange回调中,因为在回调执行成功的值之前,消息,Last将是未定义的。
this.success = success;
this.message = message;
this.Last = Last;
第二个:将此更改为在tickerBittrex函数中定义的self,因此可以使此对象正确。
var self = this;
所以:
self.success = success;
self.message = message;
self.Last = Last;