php - Ajax 响应不会打印到目标元素中?
问题描述
我一直在使用 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>
解决方案
如果它是一个 JSON 对象,也许您需要对其进行字符串化。你能试试:$('.ajaxResponse').text(JSON.stringify(response));
推荐阅读
- ios - JSONSerialization.jsonObject for complex array
- angular - 如何使用 Cypress 处理去抖动(使用 RxJs debounceTime)事件发射器?
- azure - 如何将 Azure API 管理开发人员门户更改从一个实例发布到另一个实例?
- java - 表中未显示数据
- multithreading - 产生线程并获得未来结果的最佳方法是什么?
- git - Git如何解析日期字符串?
- angular - 如何在 Angular 中从服务中填充列表数据
- sql - Skip Update of Table when no records present-SQL
- javascript - Javascript 在请求中不包括表单数据
- android - sqlite 按包含带逗号分隔符的数字的字符串排序