В настоящее время я разрабатываю веб-сайт, который просит пользователя выбрать из списка золото или серебро, а затем передать его в файл JS, который затем сделает запрос API для отображения текущего значения выбранного металла. Результат должен появиться на экране без перезагрузки всей страницы. Проблема в том, что когда я загружаю страницу, ничего не происходит. При загрузке на странице должно отображаться значение серебра по умолчанию. Любая помощь будет оценена по достоинству.
(function($) {
// var apiKey = '348e90c9b0fdb12a5e5ca407328ffdae';
// var apiURI = 'http://apilayer.net/api';
// set endpoint and your access key
endpoint = 'live'
access_key = '348e90c9b0fdb12a5e5ca407328ffdae';
//code the quote function
function quote() {
//set variable for use in the JSON request.
var type = $('#type').val(),
//add USD to the end of the variable string, since format had the first 3 letters as the base for converting
type = type + 'USD',
// get the most recent exchange rates via the "live" endpoint:
$.ajax({
url: 'http://apilayer.net/api/' + endpoint + '?access_key=' + access_key,
dataType: 'jsonp',
success: function(json) {
// exchange rata data is stored in json.quotes
alert(json.quotes.(type);
// source currency is stored in json.source
alert(json.source);
// timestamp can be accessed in json.timestamp
alert(json.timestamp);
}
});
complete: function(req, textStatus) {
switch (req.status) {
case 404:
showError('User requested a resource which does not exist!');
break;
case 101:
showError('User did not supply am access key!');
break;
case 103:
showError('User requested a non-existent API function!');
break;
case 104:
showError('User has reached or exceeded their plan monthly API reqquest allowance');
break;
case 105:
showError('User subscription does not support API Function');
break;
case 106:
showError('User Query did not find any results');
break;
default:
break;
}
}
});
}
// event handler for when the convert button is selected
// event handler: document is ready/finished loading
$(document).ready(function() {
// event handler: form submit
$('form').submit(function(e) {
// prevent form submission
e.preventDefault();
});
// event handler: search button click
$('#quote').click(function(e) {
search();
});
search();
});
})(jQuery);<link rel = "stylesheet" href = "style.css">
<script src = "https://unpkg.com/popper.js/dist/umd/popper.min.js"></script>
<!-- jquery js file from JQuery.com -->
<script src = "https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- script to run Coin function-->
<script src = "coin.js"></script>
<header>
<h1>Silver & Gold Value</h1>
</header>
<!-- Introduction to the purpose of the program-->
<h2>Purpose</h3>
I am a big coin collector, and go to a lot of auctions. And most of the coins i purchase are made of either gold or Silver. A lot of time the only value a coin had is the amount of gold or silver the coin contains. This is whats know as a "Junk Coin".
This page hopes to help in knowing the current value of both gold and silver so that if you are ever at an auction or need to know the current value of a coin, the information is readily available.
<h2>Find Value</h2>
Select either gold or silver from the list to find its up-to-date value.
<!-- create a form that holds the list of the 2 metal options-->
<Form id = "metal">
<div class = "form-group">
<label class = "currencies" for = "type">Select a Metal:</label>
<select class = "form-control" id = "type" name = "type">
<option value='XAG' title='Silver (troy ounce)'>Sliver</option>
<option value='XAU' title='Gold (troy ounce)'>Gold</option>
</select>
</div>
<button type = "button" class = "btn btn-primary type currencies" id = "quote">Convert</button>
</form>
<h2>Results</h2>
<div id = "results" class = "d-flex flex-wrap justify-content-center"></div>
</main>Любая помощь будет оценена по достоинству. Всем спасибо
Джереми прав, вам сначала нужно научиться отлаживать свои страницы. Для вещей, связанных с ajax, вкладка Network в инструментах разработчика также очень информативна.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Откройте вашу консоль. Он говорит, что
Uncaught SyntaxError: Unexpected token .У вас есть синтаксическая ошибка после того, какtype = type + 'USD',удалил запятую. В общем, если вы загружаете сайт и ничего не происходит, а страница остается пустой, это ошибка JS, и ваша консоль сообщает вам, что происходит.