javascript - 如何使用 jQuery 为失败条件显示错误模式
问题描述
当用户提交 YES 按钮时,JS 将使用 API(JSON 数据)从后端获取数据。但我试图通过使 URL 为假来模拟错误。不幸的是,错误模式没有出现在我的 HTML 页面中,数据表只是继续加载。任何人都应该阅读下面的我的 JS 并评论结构是否正确。
HTML
<div class="modal fade" id="alert2" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm modal-dialog-centered">
<div class="modal-content bg-danger text-white">
<div class="modal-body text-center">
<h3 class="text-white mb-15">ERROR</h3>
<span>Upload Failed</span>
<button type="button" class="btn btn-light" data-dismiss="modal">Ok</button>
</div>
</div>
</div>
</div>
JS
//By default to view DataTables for Upload Page
$("#myTable").DataTable({
"ajax": {
"url": "X.X.X.X/api/managefile",
"type": "POST"
},
"columns":
[
{ "data": "filename", "className": "text-center" },
{ "data": "date", "className": "text-center" },
{ "data": "uploader", "className": "text-center" },
]
});
$(document).ready(function() {
$("#myTable").change(function() {
console.log($("#myTable").val());
if ($("#myTable").val() == "") {
$("#btnSubmit").attr('disabled', true);
}
else {
$("#btnSubmit").removeAttr("disabled");
}
});
// This will run when user click YES button
$("#btnYes").on("click",function(){
$("#myTable").DataTable( {
processing: true,
crossDomain: true, //Is this
language:
{
"loadingRecords": "<img src='images/loading.gif' />"
},
dom: 'Bfltip',
buttons: [
{
className: 'btn-export',
extend: 'csvHtml5',
text: '<i class="fa fa-file-text"></i>',
titleAttr: 'CSV'
}
],
destroy: true,
ajax: {
url: "result/managefiles.json",
type: "POST"
},
columns: [
{ data: "filename", "className": "text-center" },
{ data: "date", "className": "text-center" },
{ data: "uploader", "className": "text-center" },
],
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
$('#alert2').modal('show');
}
});
});
});
解决方案
error:
仅当服务器 (API) 返回 HTTP 错误代码时,您的 Ajax 调用中的函数才会触发。
所以有两种方法可以实现这一点,要么从服务器返回 HTTP 错误,要么在 JSON 响应中返回“成功”键,然后根据“成功”条目决定如何继续。
JSON响应 //它会是这样的
{
"success": "done" or "error"
"data": //data you want to return
}
AJAX 回调
success: function(data){
if (data.success === "error")
//show modal
else if (data.success == "success")
//proceed
}
推荐阅读
- reactjs - 如何自定义日历标题文本格式(Material UI v5 - DatePicker)
- r - R:按小时的子集数据
- sql - 根据列更改值
- java - HTTP 代理 - 上游连接错误或在标头之前断开/重置。重置原因:协议错误
- javascript - 从具有多个参数的数组中查找匹配的字符串
- sql-server - 无法通过 ODBC PSQL 驱动程序从 SSIS 访问 Postgres 视图
- json - 如何在 JSON 中分配一个值,使其成为 TypeScript 中的枚举字符串值?
- next.js - 为什么 Codesandbox 的 Next.js 项目中的全局样式不起作用,尽管在 _app.js 中进行了导入?
- regex - 在Delphi中检查字符串是否是有效的URL?
- angular - 无法读取组件处未定义的属性“接受”