为什么用$就和$。员额该API调用不工作
问题描述:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.2.1.js"></script>
<script lang="javascript">$.ready(function() {
$.post("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR,GBP", function(data) {
alert(data)
})
}) </script>
</head>
<body>
</body>
</html>
这是为了拉{ “BTC”:0.0684, “USD”:294.38, “欧元”:251.24, “英镑”:227.87 }来自cryptocompare API,然后发出警报,但它什么也没有显示。我也检查devtools和没有任何传出
答
我认为你正在寻找$.get()
不是$.post()
这应该工作。
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.2.1.js"></script>
<script lang="javascript">$(document).ready(function() {
$.get("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR,GBP", function(data) {
alert(data)
})
}) </script>
</head>
<body>
</body>
</html>
答
兼用
$(document).ready(function(){
});
OR
$(function(){
})
没有什么后,可能需要$.get()
$(function() {
$.get("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR,GBP", function(data) {
alert(data)
console.log(data)
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答
您的ready
语法不正确。此外,在这种情况下,您可以只使用$.get
,尽管它可以以任何方式工作。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script lang="javascript">$(document).ready(function() {
$.get("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR,GBP", function(data) {
alert(JSON.stringify(data))
})
}) </script>
</head>
<body>
</body>
</html>
答
你想要的是可能$.get()
而不是$.post()
。
虽然$.post(url, data, handler)
通常用于POST(或$.get(url, handler)
为GET),这将是preferrable使用.done()
和.fail()
:
$.post("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR,GBP", {
"field1" : "value1",
"field2" : "value2"
}).done(function(data) {
alert('Success: ' + data);
}).fail(function(xhr, status, error) {
alert('Error: ' + error);
});
对于GET:
$.get("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR,GBP").done(function(data) {
alert('Success: ' + data);
}).fail(function(xhr, status, error) {
alert('Error: ' + error);
});
另外请注意,这应该当DOM准备就绪时(如果您需要将数据添加到某个HTML元素或类似的东西):
<script type="text/javascript">
$(document).ready(function() {
// Here
});
</script>
不应该'$ .ready'是'$(document).ready'? https://api.jquery.com/ready/ – bassxzero
你在哪里传递POST数据?我相信它应该是'$ .post(“https:// ...”,{“field”:“value”},function(data){alert(data);});'。也许你想使用'.get()'? –