2014-09-22 26 views
0

我想做一些看起來夠簡單的事情,但我掙扎了很多(我是Javascript的新手)。從api獲取價值並使用javascript顯示

我想從此頁面獲得價值https://blockchain.info/q/24hrprice(比特幣api價格)。我想把它放在一個JavaScript變量中,然後將其顯示在我的網頁上。

這裏就是我有這麼遠:

<input type="text" id="mytext"> 

<script> 
var test = $.getJSON("https://blockchain.info/q/24hrprice"); 
var todayvalue = test.done(function(response) { console.log(response); }); 
document.getElementById("mytext").value = todayvalue; 
</script> 

如果我檢查我的控制檯,價值被發現,沒有錯誤消息,但我得到我的網頁是[對象的對象]一箱並沒有什麼。

你們知道我在做什麼錯嗎?

多謝

+1

寫行'的document.getElementById(「mytext的」)值=響應;'回調函數 – Sunand 2014-09-22 22:11:30

+0

裏面你忘記了,你的Ajax調用是異步的。在這裏看到相關的答案:http://stackoverflow.com/a/14220323/361762 – dave 2014-09-22 22:15:38

+0

可能重複的[如何從Ajax調用返回響應?](http://stackoverflow.com/questions/14220321/how-to -return-the-a-an-ajax-call) – dave 2014-09-22 22:15:49

回答

1

你會希望把document.getElementById("mytext").value = response;你的成功回調。

var promise = $.getJSON("https://blockchain.info/q/24hrprice"); 

promise.done(function(todayValue) { 
    console.log(todayValue); 
    document.getElementById("mytext").value = todayValue; 
}); 
0

$.getJSON()(和$.getJSON.load())返回一個jqXHR對象,這是你在你的varaible todayvalue得到。

訪問響應在回調從$.getJSON()

做,因爲你已經加載了jQuery,堅持到底。下面是和例子你可能想要做:

$.getJSON("https://blockchain.info/q/24hrprice", function(response){ 
     $("#mytext").val(response); 
    });