使用jQuery,我用包含两个文本框和一个按钮的表单动态替换Div的内容。单击此按钮后,根据文本框收集的数据,使用AJAX从公共网络服务中获取结果。代码:
$(document).ready(function () {
$(document).on('submit', '#formId', function (e) {
e.preventDefault();
$("#formId").on("click", "#btnShowCurrency", function (event) {
var currencyCode = $('#txtCode').val();
var currencyDate = $('#txtDate').val();
var urlWithVar = 'http://api.nbp.pl/api/exchangerates/rates/a/' + currencyCode + '/' + currencyDate + '/?format=json';
var urlWithoutVar = 'http://api.nbp.pl/api/exchangerates/rates/a/usd/2018-03-26/?format=json';
$.ajax({
url: urlWithVar,
type: "GET",
dataType: "json",
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "rn" + xhr.statusText + "rn" + xhr.responseText);},
success: function (parsed_json) {
var currency = parsed_json['currency'];
var code = parsed_json['code'];
var mid = parsed_json['rates']['0']['mid'];
var effectiveDate = parsed_json['rates']['0']['effectiveDate'];
alert("Average exchange rate for: " + currency + " [" + code + "]" + ", day: " + effectiveDate + ", is: " + mid);}
});
});
});
});
所以,当我使用硬编码 urlwithoutvar 时,它可以毫无问题。但是,当使用 urlwithvar 时,会提出404个毫无根据的错误。我很困惑,有人可以帮忙吗?
我认为您尝试了USD而不是美国,无论哪种方式,我都将链接与Urlwithvar一起使用,这是我的代码(我也简化了一点点代码(
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#btnShowCurrency").click(function (e) {
var currencyCode = $('#txtCode').val();
var currencyDate = $('#txtDate').val();
var urlWithVar = 'http://api.nbp.pl/api/exchangerates/rates/a/' + currencyCode + '/' + currencyDate + '/?format=json';
var urlWithoutVar = 'http://api.nbp.pl/api/exchangerates/rates/a/usd/2018-03-26/?format=json';
$.ajax({
url: urlWithVar,
type: "GET",
dataType: "json",
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
},
success: function (parsed_json) {
var currency = parsed_json['currency'];
var code = parsed_json['code'];
var mid = parsed_json['rates']['0']['mid'];
var effectiveDate = parsed_json['rates']['0']['effectiveDate'];
alert("Average exchange rate for: " + currency + " [" + code + "]" + ", day: " + effectiveDate + ", is: " + mid);}
});
});
});
</script>
</head>
<body>
<form id='formId'>
<input type='text' id='txtCode' value='usd'/>
<input type='text' id='txtDate' value='2018-03-26'/>
<input type='button' value='Submit' id='btnShowCurrency'/>
</form>
</body>
</html>
好吧,看来我有点愚蠢。我在文本框中键入了另一个日期 - 我开玩笑地意识到那是星期天。而且该公共网络服务仅在工作日才能获得...
所以我的代码正确 - 希望将来会帮助某人!