我正在尝试从这个 api 获取一些数据:
https://www.bitstamp.net/api/ticker/
放入 jquery 变量(最终显示在网页上)。它返回一个 JSON 字典(更多信息在这里 https://www.bitstamp.net/api/ )。
我连续几个小时都尝试在所有客户端执行此操作,但意识到我做不到,因为该 api 不支持跨域请求和 JSONP。所以我然后转向服务器端代码:
我有一个包含以下代码的 php 文件“test.php”:
<?php
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>
然后在我的 html 页面中有以下代码:
<script>
var last = JSON.parse(test.php)["last"]
document.getElementById('apidata').innerHTML=last;
</script>
<span id="apidata"></span>
但我不知道为什么它不起作用!任何人都可以阐明这一点吗?
我认为 jquery 可能更简单,但如果有人知道如何使用 JS 完成此操作,我也很想听听。我也怀疑我的php文件有误。
编辑:这是我的 php 文件的链接 http://www.buyabitcoin.co.uk/beta/test/test.php 和我的 html 文件 http://www.buyabitcoin.co.uk/beta/test/test.html
用户名:'test' 密码:'test123'
编辑:我也试过
$.getJSON('test.php', function(response) {$("#apidata").html(response.value); });
在 html 中,但无济于事。谁能确认我的 php 输出的是 JSON 而不是字符串?
提前致谢
最佳答案
像这样修改你的 php 文件:
<?php
header('Content-type: application/json');
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>
header()告诉请求实体它提供什么样的数据。 您请求的 url ( 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"
}
你的 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
});
关于php - 从 JSON API 获取数据到 JS 或 jquery 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16161986/