比特币 - 用于返回当前BTC汇率的JavaScript函数

时间:2017-06-12 01:26:06

标签: javascript bitcoin

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

到目前为止,这是我的代码:

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指出这一点。

2 个答案:

答案 0 :(得分:0)

我的第一个想法是像这样使用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>" );
    }
  });   
}

我知道这似乎是“过于具体”的答案,但这是我的方法。

答案 1 :(得分:0)

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 // or bid or last

demo