Reputation: 111
I want to get JSON from the URL, but jQuery's function getJSON doesn't work. I got this error: "Failed to load https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access." What did I do wrong? Or should I use some other fucntion? Please help!
function ticker(url)
{
this.Last = 0;
$.getJSON(url, function(data)
{
this.Last = data.result.Last;
});
this.getFullInfo = function()
{
console.log("Last: " + this.Last);
}
}
var usdtBTC = new ticker("https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc");
usdtBTC.getFullInfo();
Upvotes: 0
Views: 96
Reputation: 2855
A few things are wrong:
That URL isn't accessible via AJAX for the whole world to see. Read up on CORS. The error actually comes from a HEAD
request that the browser does automatically to see what hosts & methods are allowed to access the link.
You need to bind the this
param to the function or this
will refer to the global scope (function-in-a-function):
$.getJSON(url, function(data) {
this.Last = data.result.Last;
}.bind(this));
If the request worked, you'd need to wait until the request had finished before calling getFullInfo()
(just like a timeout), or this.Last
would still be 0.
You nearly always want to add a fail function especially when testing:
var url = "https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc";
$.getJSON(url, function(data) {
console.log(data.result);
}.bind(this))
.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2