Я возился с postcodes.io, чтобы создать простую форму для поиска данных по почтовому индексу пользователей. Я могу нормально запросить postcodes.io и получить ответ, который вы можете увидеть в журнале консоли. Но по какой-то причине я не могу получить ответ на печать в целевой элемент, в моем случае $('.ajaxResponse').html(response);
Я нахожусь в тупике, любая помощь будет безумно благодарна.
$(document).ready(function() {
$('#ajaxSubmit').click(function() {
$.ajax({
type: "get",
url: 'https://api.postcodes.io/postcodes/' + $('#userPostCode').val(),
dataType: 'json',
success: function(response) {
console.log(response); // Returns data;
console.log($('.ajaxResponse')); // Is descoverable
$('.ajaxResponse').html(response); // Not working ?
},
error: function(xhr, ajaxOptions, thrownError) {
var msg = '';
if (xhr.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (xhr.status == 404) {
msg = 'Requested page not found. [404]';
} else if (xhr.status == 500) {
msg = 'Internal Server Error [500].';
} else if (thrownError === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (thrownError === 'timeout') {
msg = 'Time out error.';
} else if (thrownError === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + xhr.responseText;
}
}
});
});
$('#ajaxSubmit').submit(function(e) {
e.preventDefault();
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jumbotron">
<h1>Search Postcodes.io</h1>
<form method="get" action="">
<div class="form-row align-items-center mb-3">
<div class="col-auto">
<label class="sr-only" for="userPostCode">Postcode</label>
<input type="text" name="postcode" class="form-control form-control-lg mb-2" id="userPostCode" placeholder="AL1 2BQ" required>
</div>
<div class="col-auto">
<button type="button" id="ajaxSubmit" class="btn btn-lg btn-primary mb-2">Submit</button>
</div>
</div>
</form>
<p>The response:</p>
<div class="ajaxResponse"></div>
</div>