简体   繁体   English

将数据从JSON API获取到JS或jquery变量中

[英]Get data from a JSON API into JS or jquery variable

I am trying to get some data from this api: 我正在尝试从此api获取一些数据:

https://www.bitstamp.net/api/ticker/ https://www.bitstamp.net/api/ticker/

into a jquery variable (to eventually display on a web page). 放入一个jquery变量(最终显示在网页上)。 It returns a JSON dictionary (more information here https://www.bitstamp.net/api/ ). 它返回一个JSON字典(更多信息, 请参见https://www.bitstamp.net/api/ )。

I tried for hours on end doing it all client side but realised that I cant because the api doesn't support cross-origin requests nor JSONP. 我尝试了数小时才在客户端完成所有操作,但意识到我做不到,因为api不支持跨域请求或JSONP。 So I then moved onto serverside code: 因此,我接着转到服务器端代码:

I have a php file 'test.php' with the following code: 我有一个带有以下代码的php文件“ test.php”:

<?php
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>

Then inside my html page I have the following code: 然后在我的html页面中,我有以下代码:

<script>
var last = JSON.parse(test.php)["last"]
document.getElementById('apidata').innerHTML=last;
</script>
<span id="apidata"></span>

But I don't know why it's not working! 但是我不知道为什么它不起作用! Can anyone please shed some light on this? 任何人都可以对此有所了解吗?

I thought jquery may be simpler but if anyone knows how to get this done with JS I'd like to hear that too. 我以为jquery可能更简单,但是如果有人知道如何用JS完成此操作,我也想听听。 I also suspect that my php file is wrong. 我也怀疑我的php文件是错误的。

EDIT: Here's a link to my php file http://www.buyabitcoin.co.uk/beta/test/test.php and my html file http://www.buyabitcoin.co.uk/beta/test/test.html 编辑:这是我的php文件http://www.buyabitcoin.co.uk/beta/test/test.php和我的html文件http://www.buyabitcoin.co.uk/beta/test/test的链接。 HTML

username: 'test' password: 'test123' 用户名:“ test”密码:“ test123”

EDIT: I have also tried 编辑:我也尝试过

$.getJSON('test.php', function(response) {$("#apidata").html(response.value); });

in the html but to no avail. 在HTML,但无济于事。 Can anyoneplease confirm if my php is outputting a JSON rather than a string? 任何人都可以确认我的PHP是否输出JSON而不是字符串?

Many thanks in advance 提前谢谢了

You can use jQuery ajax function to get JSON from the php page 您可以使用jQuery ajax函数从php页面获取JSON

like, 喜欢,

$.ajax({
    dataType: "json",
    url: 'test.php',
    data: data,
    success: function(data){
        var last = data.last
        $('#apidata').innerHTML=last;
    }
});

Read more about jQuery.ajax http://api.jquery.com/jQuery.ajax/ 阅读有关jQuery.ajax更多信息http://api.jquery.com/jQuery.ajax/

Modify your php file like so: 像这样修改您的php文件:

<?php
header('Content-type: application/json');
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>

The header() tells the requesting entity what sort of data it provides. header()告诉请求实体它提供什么样的数据。 The url you request ( https://www.bitstamp.net/api/ticker/ ) provides this json string: 您请求的网址( https://www.bitstamp.net/api/ticker/ )提供了以下json字符串:

{
    "high": "161.00",
    "last": "154.00",
    "bid": "153.51",
    "volume": "20295.34112055",
    "low": "135.10",
    "ask": "154.00"
}

Your html page has this JQuery: 您的html页面具有以下JQuery:

$.getJSON('test.php', function(response) {
    // access the response here
    // e.g. get the volume
    var volume = parseInt(response.volume);
    // the numbers are returned as strings (numbers in quotes), thats why parseInt should be used
});

You do not need to have jQuery just to download a JSON string and replace a div's content! 您不需要仅使用jQuery就可以下载JSON字符串并替换div的内容!

function loadXMLDoc() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            r = JSON.parse(xmlhttp.responseText);
            document.getElementById("apidata").innerHTML=r;
        }
    }

    xmlhttp.open("GET","/beta/test/test.php",true);
    xmlhttp.send();
}

loadXMLDoc();

I managed to do what I want with the following code. 我设法用下面的代码做我想做的事。 This allows me to 'extract' a value from the JSON (in this example, the value for 'last') to use as a JS variable in a separate html file: 这使我可以从JSON中“提取”一个值(在本示例中为“ last”的值),以用作单独的html文件中的JS变量:

In my php file: 在我的php文件中:

<?php
$ticker = file_get_contents('https://www.bitstamp.net/api/ticker/');   
$obj = json_decode($ticker,true); // Split the JSON into arrays.
echo json_encode(array("myVariable" => $obj['last']));
?>

In my html file: 在我的html文件中:

$.getJSON('test.php', function(data) {
var myVar = data.myVariable }); 

I hope this helps someone. 我希望这可以帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM