Bitcoin-返回当前BTC汇率的JavaScript函数

Bitcoin-返回当前BTC汇率的JavaScript函数,javascript,bitcoin,Javascript,Bitcoin,我想写一个JavaScript函数,返回当前的BTC/USD汇率。我做了一些研究,但我只想要一些简单的东西。它不会在服务器端用于计算值(明显的安全隐患),只是为了方便我的用户。我有两个文本字段,当用户更改其中一个值时,它将更新另一个字段 以下是我目前的代码: var getBTCRate = function(){ /* code here */ }; var btcprice = getBTCRate(); // update the BTC value as the USD value

我想写一个JavaScript函数,返回当前的BTC/USD汇率。我做了一些研究,但我只想要一些简单的东西。它不会在服务器端用于计算值(明显的安全隐患),只是为了方便我的用户。我有两个文本字段,当用户更改其中一个值时,它将更新另一个字段

以下是我目前的代码:

var getBTCRate = function(){ /* code here */ };

var btcprice = getBTCRate();

// update the BTC value as the USD value is updated
$("#usdvalue").keyup(function(ev){
    var usdvalue = $("#usdvalue").val();
    $("#btcvalue").val(usdvalue / btcprice);
});

// update the USD value as the BTC value is updated
$("#btcvalue").keyup(function(ev){
    var btcvalue = $("#btcvalue").val();
    $("#usdvalue").val(btcvalue * btcprice);
});
简单明了。在我的研究中,我没有找到能够做到这一点的方法,只有一堆令人困惑的API。非常感谢您的帮助

编辑以修复代码中的错误


再次编辑以固定函数声明的位置。感谢@RobG指出了这一点。

我的第一个想法是像这样使用JQuery负载

$.get('https://www.google.com/search?q=btc+value', function(p) {
  console.log(p);
}); 
但跨原产地规则阻止了我。 现在,你可以为一个有API的服务付费,但我想不用付费就可以做到。我最终做的是一个基于服务器的解决方案。我使用PowerBasic作为后端,并使用SocketTools库

#COMPILE EXE
#DIM ALL
#Include "pbcgi.inc"
#Include "C:\bas_src\socketTools\v9.5\inc\cstools9.inc"     

Function PBMain () As Long         
    Local btc As String         
    Local html As String   

    html= httpGet("https://www.google.com/search?q=btc+value")      

    ' filter out just the current BTC value
    ' by looking for what is between the words "Bitcoin =" and "United States Dollar"
    btc=Remain$(html,"Bitcoin =")     
    btc=Extract$(btc,"United States Dollar")
    btc=Trim$(btc)

    writeCGI "{"+jsonPad("btc")+":"+jsonPad(btc)+","+jsonPad("error")+":"+jsonPad("0")+"}"


END FUNCTION

'================================================================
' retrieve the page and return it as a string
Function httpGet(ByVal URL As String) As String

    If IsFalse( HttpInitialize($CSTOOLS9_LICENSE_KEY) ) Then
        Function="unable to init socket library"
        Exit Function
    End If         

  Local hClient      As Dword
  Local lpszURL      As STRINGZ * 4096
  Local lpszBuffer   As STRINGZ * 100000
  Local httpContents As String
  Local httpPort     As Long
  Local httpOptions  As Dword
  Local nResult      As Long

  If LCase$(Trim$(Left$(URL, 8))) = "https://" Then
     httpPort    = 443
     httpOptions = %HTTP_OPTION_SECURE Or %HTTP_OPTION_REDIRECT
  Else
     httpPort    = 80
     httpOptions = %HTTP_OPTION_REDIRECT
  End If

  lpszURL = URL & Chr$(0)

  hClient = HttpConnect(lpszURL, _
                        httpPort, _
                        %HTTP_TIMEOUT, _
                        httpOptions, _
                        %HTTP_VERSION_10)

  If hClient = %INVALID_CLIENT Then
      Function = "Could not connect to: " & URL
      Exit Function
  End If

  HttpSetEncodingType(hClient, %HTTP_ENCODING_NONE)
  nResult = HttpGetText(hClient, lpszURL, lpszBuffer, 100000)

  If nResult = %HTTP_ERROR Then
      Function = "Error retrieving file."+Str$(nResult)
  Else    
      ' success
      httpContents = lpszBuffer     
      Function =httpContents    
  End If

  Call HttpDisconnect(hClient)        
  HttpUninitialize()

End Function
'================================================================


' pad string for json return
Function jsonPad(jstr As String) As String       
  Local i As Long

  Replace Chr$(10) With " " In jstr    
  Replace Chr$(13) With " " In jstr    
  Replace "\" With "\\" In jstr  
  Replace $Dq With "\"+$Dq In jstr   

  For i = 0 To 9
    Replace Chr$(i) With " " In jstr
  Next       

  Function=$Dq+Trim$(jstr)+$Dq               


End Function
在我的网页上,我称之为使用AJAX

function showBTC(){

  $.ajax({
    type: "POST",
    url: "../cgi/btcGet.exe",
    dataType: "json",
    success: function(json){       

            if(json.error !== "0" ){
                console.log( json.error );
                return;
            }

            $("#btcValue").html( "current BTC value $"+json.btc+"<br><br>" );
    }
  });   
}
函数showBTC(){
$.ajax({
类型:“POST”,
url:“../cgi/btcGet.exe”,
数据类型:“json”,
成功:函数(json){
如果(json.error!=“0”){
log(json.error);
返回;
}
$(“#BTC值”).html(“当前BTC值$”+json.BTC+”

”; } }); }
我知道这似乎是一个“太具体”的答案,但这是我如何做到的

编辑2020年11月5日: 有一种比特币API可以大大简化这一过程

const api = 'https://apiv2.bitcoinaverage.com/indices/local/ticker/short?crypto=BTC&fiat=USD'
$.get(api, p => {
  document.querySelector('pre').textContent = JSON.stringify(p, null, 2)
}); 
结果

{
  "BTCUSD": {
    "ask": 3594.5649555077953,
    "timestamp": 1550284932,
    "bid": 3591.715961836563,
    "last": 3592.745617344171,
    "averages": {
      "day": 3583.13243402
    }
  }
}
因此,选择
p.BTCUSD.ask//或出价或最后一次


问题出在哪里?我找不到一个能满足我需要的函数,我很好奇是否有人知道这样一个函数。这是我在几乎所有比特币交换上看到的非常基本的功能,但似乎找不到实现它的方法。返回JSON。@obsidiange这将如何实现?它提供了比我需要的更多的信息。也许这就是你想要的?