我有一个小项目,需要在其中插入/编辑/删除JSON文件中的记录。我为此项目使用http://myjson.com/
API(不确定这是否是最好的解决方案,也许其他来源的API更好)。我正在尝试从json文件中删除记录,但我不确定该怎么做。有什么方法可以使用此API做到这一点?这里有关于如何向json文件添加/更新记录的说明,但是没有关于如何删除记录的说明。这是我的代码示例:
var contactStorage = {};
/*** Start: Build Datatables function. ***/
function buildDataTable(tblID, columnsArray, displayLength) {
$('#' + tblID).DataTable({
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
"iDisplayLength": displayLength,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': columnsArray
}],
"language": {
"emptyTable": "No records were found."
}
});
}
/*** End: Build Datatables function. ***/
/*** Start: Phone number format for US standard. ***/
$('.us-phone').on("keypress", formatPhoneUS);
function formatPhoneUS(e) {
var output,
inputVal = $(this).val().replace(/[^0-9]/g, ''),
area = inputVal.substr(0, 3),
pre = inputVal.substr(3, 3),
tel = inputVal.substr(6, 4);
if (parseInt(inputVal, 10)) {
if (area.length < 3) {
output = "(" + area;
} else if (area.length === 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length === 3 && pre.length === 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
}
if (e.key === 'Backspace') return;
$(this).val(output);
};
/*** End: Phone number format for US standard. ***/
$("#frm_find").on("submit", findContacts);
function findContacts(e) {
e.preventDefault();
var frmFilter = $("#frm_filterby").val();
if (frmFilter) {
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/7iig8?' + new Date().getTime(),
dataType: 'json'
}).done(function(obj) {
contactStorage = obj.filter(function(entry) {
switch (frmFilter) {
case '1':
return entry.status === 1;
break;
case '2':
return entry.status === 0;
break;
default:
return entry;
}
});
showContacts(contactStorage);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + errorThrown);
});
}
}
function showContacts(contactStorage) {
var contactsTbl = "<table id='contactsTbl' class='table table-bordered'><thead><tr><th>Last</th><th>First</th><th>Email</th><th>Phone</th><th>Status</th><th class='text-center'>Edit</th><th class='text-center'>Delete</th></tr></thead><tbody>";
if (contactStorage) {
for (var key in contactStorage) {
contactsTbl += "<tr id='" + $.trim(contactStorage[key].id) + "'><td>" + $.trim(contactStorage[key].last) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].first) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].email) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].phone) + "</td>";
contactsTbl += "<td>" + $.trim(contactStorage[key].status === 1 ? 'Active' : 'Inactive') + "</td>";
contactsTbl += "<td class='text-center'><button class='btn btn-default btn-sm contact_edit' data-toggle='collapse' data-target='#save_contact,#search_contact'><span class='glyphicon glyphicon-edit'></span></button></td>"
contactsTbl += "<td class='text-center'><button class='btn btn-default btn-sm contacts_delete'><span class='glyphicon glyphicon-remove'></span></button></td></tr>";
}
}
contactsTbl += "</tbody></table><div class='row'><div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'><div id='contact_message' class='alert message-submit'></div></div></div>";
$('#contacts_list').empty().append(contactsTbl).show();
buildDataTable('contactsTbl', [5, 6], 10);
}
var deleteID, targetTr;
$("#contacts_list").on("click", ".contacts_delete", displayContact);
function displayContact() {
deleteID = $(this).closest('tr').attr('id'), // Get record ID.
targetTr = $(this).parents('tr');
var lastName = targetTr.find("td").eq(0).text(),
firstName = targetTr.find("td").eq(1).text(),
bodyContent = $('<p>You are about to delete record for <b>' + lastName + ', ' + firstName + '</b>.<p>Do you want to proceed?</p>');
$('#delete_modalBody').empty().append(bodyContent); // Append elements to body content.
$('#deleteModal').modal('show'); // Show delete modal box.
}
$("#deleteModal").on("click", ":button.confirm_delete", removeContact);
function removeContact() {
if (deleteID) {
var table = $("#contactsTbl").DataTable(); // Select DataTable by ID.
table.row(targetTr).remove().draw(); // Remove record from DataTable.
delete contactStorage[deleteID]; // Remove element from JS object.
$("#contact_message").show().addClass("alert-success").html("Record successfully removed.").delay(5000).fadeOut('slow').queue(function() {
$(this).removeClass("alert-success").dequeue();
});
} else {
$("#contact_message").show().addClass("alert-danger").html("Error! Please contact your administrator.").delay(5000).fadeOut('slow').queue(function() {
$(this).removeClass("alert-danger").dequeue();
});
}
}
div.container {
padding-top: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Application</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- *** Start: JS and CSS for DataTables. *** -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.4.2/js/buttons.print.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.jqueryui.min.css" />
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css" />
<!-- *** End: JS and CSS for DataTables. *** -->
<link rel="stylesheet" type="text/css" href="App.css" />
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">Welcome to Contact Application</div>
<div class="panel-body">
<div id="search_contact" class="collapse in">
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#save_contact,#search_contact">
<span class="glyphicon glyphicon-plus-sign"></span> New Contact
</button>
</div>
</div>
<form name="frm_find" id="frm_find" autocomplete="off">
<div class="row find-row">
<div class="form-group col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2">
<select class="form-control" name="frm_filterby" id="frm_filterby" required>
<option value="">--Choose--</option>
<option value="1">Active</option>
<option value="2">Inactive</option>
<option value="3">Show All</option>
</select>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2">
<button class="btn btn-block btn-primary" name="frm_search" id="frm_search">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</div>
</form>
<div id="contacts_list" class="table-responsive"></div>
</div>
<div id="save_contact" class="collapse">
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="button" class="btn btn-primary" data-toggle="collapse" data-target="#save_contact,#search_contact">
<span class="glyphicon glyphicon-circle-arrow-left"></span> Go Back
</button>
</div>
</div>
<form name="frm_contacts" id="frm_contacts" autocomplete="off">
<div class="form-group">
<label class="control-label" for="fname"><span class="label label-primary">First Name:</span></label>
<input type="text" class="form-control" name="frm_first" id="frm_first" placeholder="Enter First Name" maxlength="50" title="A-Z, space, dash, apostrophe, period, comma - no other special characters" pattern="[a-zA-Z][A-Za-z' .,-]{0,49}$" required>
</div>
<div class="form-group">
<label class="control-label" for="lname"><span class="label label-primary">Last Name:</span></label>
<input type="text" class="form-control" name="frm_last" id="frm_last" placeholder="Enter Last Name" maxlength="50" title="A-Z, space, dash, apostrophe, period, comma - no other special characters" pattern="[a-zA-Z][A-Za-z' .,-]{0,49}$" required>
</div>
<div class="form-group">
<label class="control-label" for="email"><span class="label label-primary">Email address:</span></label>
<input type="email" class="form-control" name="frm_email" id="frm_email" placeholder="Enter Email" maxlength="80" required>
</div>
<div class="form-group required">
<label class="control-label" for="phone"><span class="label label-primary">Phone:</span></label>
<input type="tel" class="form-control us-phone" name="frm_phone" id="frm_phone" pattern="\(\d{3}\)[ ]?\d{3}[-]?\d{4}" maxlength="14" title="US based Phone Number in the format of: (xxx) xxx-xxxx" placeholder="(xxx) xxx-xxxx" required>
</div>
<div class="form-group required">
<label class="control-label" for="status"><span class="label label-primary">Status:</span></label>
<select class="form-control" name="frm_status" id="frm_status" required>
<option value="">--Choose--</option>
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
<button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-11 col-lg-11">
<div id="frm_message" class="alert alert-Submit"></div>
</div>
</div>
</form>
</div>
</div>
<div class="panel-footer">
<p><span>© 2018 MD. All Rights Reserved.</span></p>
</div>
</div>
</div>
<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirm Delete</h4>
</div>
<div class="modal-body" id="delete_modalBody"></div>
<div class="modal-footer" id="delete_modalFooter">
<button type="button" class="btn btn-warning confirm_delete" data-dismiss="modal">Delete</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<script language="javascript" src="App.js"></script>
</body>
</html>
如果有人知道如何实现此目的,或者可以将其他一些API用于此目的,请告诉我。