jquery错误时使用我的ajax设置与url/${}删除动态行



当我把url与${id},我得到一个错误说id没有定义

var settings = {
"async": true,
"crossDomain": true,
"url": `https://example.restdb.io/rest/example/${id}`,
"method": "DELETE", // delete based on ID
"headers": {
"content-type": "application/json",
"x-apikey": APIKEY,
"cache-control": "no-cache"
}
}

//[STEP 0]: Make sure our document is A-OK
$(document).ready(function () {
//what kind of interface we want at the start 
const APIKEY = "32187321dkasahjsdaaj"; // fake
getContacts();
$("#update-contact-container").hide();
$("#add-update-msg").hide();
//[STEP 1]: Create our submit form listener = SEND
$("#contact-submit").on("click", function (e) {
//prevent default action of the button 
e.preventDefault();
//[STEP 2]: ONCE CLICK 
// let's retrieve form data
//for now we assume all information is valid
//you are to do your own data validation
// get the value from html's elements
let contactName = $("#contact-name").val();
let contactID_1 = $("#contact-ID-1").val();
let contactMentor = $("#contact-mentor").val();
let contactClass = $("#contact-class").val();
let contactEmail = $("#contact-email").val();
let contactPhone = $("#contact-phone").val();
//[STEP 3]: get form values when user clicks on SEND
//Adapted from restdb api
let jsondata = {
"name": contactName,
"student_id": contactID_1,
"mentor": contactMentor,
"class": contactClass,
"email": contactEmail,
"phone": contactPhone
};
//[STEP 4]: Create our AJAX settings. Take note of API key
let settings = {
"async": true,
"crossDomain": true,
"url": "https://example.restdb.io/rest/studentcrud",
"method": "POST", // we will use post to send info to server to update
"headers": {
"content-type": "application/json",
"x-apikey": APIKEY,
"cache-control": "no-cache"
},
"processData": false,
"data": JSON.stringify(jsondata),
"beforeSend": function () {
//beforeSend - what to do before request is sent
//@TODO use loading bar instead
//disable our button or show loading bar
$("#contact-submit").prop("disabled", true);
//clear our form using the form id and triggering it's reset feature
$("#add-contact-form").trigger("reset");
}
}
//[STEP 5]: Send our ajax request over to the DB and print response of the RESTDB storage to console.
$.ajax(settings).done(function (response) {
console.log(response);
$("#contact-submit").prop("disabled", false);
//@TODO update frontend UI 
$("#add-update-msg").show().fadeOut(3000); //Contact record successfully added
//update our table 
getContacts();
});
});//end click 
//[STEP] 6
//let's create a function to allow you to retrieve all the information in your contacts
//by default we only retrieve 10 results
function getContacts(limit = 10, all = true) {
//[STEP 7]: Create our AJAX settings
let settings = {
"async": true,
"crossDomain": true,
"url": "https://example.restdb.io/rest/studentcrud",
"method": "GET", //[cher] we will use GET to retrieve info
"headers": {
"content-type": "application/json",
"x-apikey": APIKEY,
"cache-control": "no-cache"
},
}
//[STEP 8]: Make our AJAX calls
//Once we get the response, we modify our table content by creating the content internally. We run a loop to continously add on data
//RESTDb/NoSql always adds in a unique id for each data, we tap on it to have our data and place it into our links 
$.ajax(settings).done(function (response) {
let content = "";
for (var i = 0; i < response.length && i < limit; i++) {
content = `${content}<tr id='${response[i]._id}'>
<td>${response[i].name}</td>
<td>${response[i].student_id}</td> 
<td>${response[i].mentor}</td>
<td>${response[i].class}</td>
<td>${response[i].email}</td>
<td>${response[i].phone}</td>
<td><a href='' class='delete' data-id='${response[i]._id}'>Del</a></td>
<td><a href='#update-contact-container' class='update' data-id='${response[i]._id}' data-student_id='${response[i].student_id}' data-mentor='${response[i].mentor}' data-class='${response[i].class}' data-phone='${response[i].phone}' data-name='${response[i].name}' data-email='${response[i].email}'>Update</a></td></tr>`;
}
//[STEP 9]: Update our HTML content
//let's dump the content into our table body
$("#contact-list tbody").html(content);
$("#total-contacts").html(response.length); // update the no. of contacts
});
// this entire is getContact;
}
//[STEP 10]: Create our update listener
//here we tap onto our previous table when we click on update
//this is a delegation feature of jquery
//because our content is dynamic in nature, we listen in on the main container which is "#contact-list". For each row we have a class .update to help us
$("#contact-list").on("click", ".update", function (e) {
e.preventDefault();
//update our update form values
//UPDATE FORM
let contactName = $(this).data("name");
let contactID_1 = $(this).data("student_id");
let contactId = $(this).data("id");
let contactMentor = $(this).data("mentor");
let contactClass = $(this).data("class");
let contactEmail = $(this).data("email");
let contactPhone = $(this).data("phone");
//[STEP 11]: Load in our data from the selected row and add it to our update contact form 
$("#update-contact-name").val(contactName);
$("#update-contact-ID-1").val(contactID_1);
$("#update-contact-id").val(contactId);
$("#update-contact-mentor").val(contactMentor);
$("#update-contact-class").val(contactClass);
$("#update-contact-email").val(contactEmail);
$("#update-contact-phone").val(contactPhone);
$("#update-contact-container").show();
});//end contact-list listener for update function
//[STEP 12]: Here we load in our contact form data
//Update form listener
$("#update-contact-submit").on("click", function (e) {
e.preventDefault();
//retrieve all my update form values
let contactName = $("#update-contact-name").val();
let contactID_1 = $("#update-contact-ID-1").val();
let contactMentor = $("#update-contact-mentor").val();
let contactClass = $("#update-contact-class").val();
let contactEmail = $("#update-contact-email").val();
let contactPhone = $("#update-contact-phone").val();
let contactId = $("#update-contact-id").val();
//[STEP 12a]: We call our update form function which makes an AJAX call to our RESTDB to update the selected information
updateForm(contactId, contactName, contactID_1, contactMentor, contactClass, contactEmail, contactPhone);
});//end updatecontactform listener
//[STEP 13]: function that makes an AJAX call and process it 
//UPDATE Based on the ID chosen
function updateForm(id, contactName, contactID_1, contactMentor, contactClass, contactEmail, contactPhone) {
//@TODO create validation methods for id etc. 
var jsondata = { "name": contactName, "student_id": contactID_1, "mentor": contactMentor, "class": contactClass, "email": contactEmail, "phone": contactPhone };
var settings = {
"async": true,
"crossDomain": true,
"url": `https://example-95e6.restdb.io/rest/studentcrud/${id}`,//update based on the ID
"method": "PUT",
"headers": {
"content-type": "application/json",
"x-apikey": APIKEY,
"cache-control": "no-cache"
},
"processData": false,
"data": JSON.stringify(jsondata)
}
//[STEP 13a]: send our AJAX request and hide the update contact form
$.ajax(settings).done(function (response) {
console.log(response);
$("#update-contact-container").fadeOut(5000);
//update our contacts table
getContacts();
});
}//end updateform function
//[STEP 14]: Create EVENT LISTENER ON delete 
$("#contact-list").on("click", ".delete", function (e) {
e.preventDefault();
console.log("hello")
var settings = {
"async": true,
"crossDomain": true,
"url": `https://example-95e6.restdb.io/rest/studentcrud/${id}`,
"method": "DELETE", // delete based on ID
"headers": {
"content-type": "application/json",
"x-apikey": APIKEY,
"cache-control": "no-cache"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
console.log('hi hi');
//update our table 
getContacts();
});
});
}) // end
html, body {
height: 100%;
width: 100%;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
<div class="container">
<h1>Simple Contact Form System</h1>
<div id="add-update-msg">
<!-- will be hide away -->
<div class="alert alert-success" role="alert">Contact record successfully added</div>
</div>
<div class="form" id="add-contact">
<form id="add-contact-form">
<!-- Input -->
<!-- Name -->
<div class="form-group"><label for="contact-name">Name</label><input type="text" id="contact-name"
class="form-control" required></div><!-- Student ID -->
<div class="form-group"><label for="contact-ID-1">Student ID</label><input type="tel" id="contact-ID-1"
class="form-control" required></div><!-- Mentor -->
<div class="form-group"><label for="contact-mentor">Student Mentor</label><input type="text" id="contact-mentor"
class="form-control" required></div><!-- Class -->
<div class="form-group"><label for="contact-class">Class</label><input type="text" id="contact-class"
class="form-control" required></div><!-- Email -->
<div class="form-group"><label for="contact-email">Email</label><input type="email" id="contact-email"
class="form-control" required><small id="contact-email-help" class="form-text text-muted">We'll never share
your email with anyoneelse.</small></div><!-- Phone -->
<div class="form-group"><label for="contact-phone">Phone Number</label><input type="tel" id="contact-phone"
class="form-control"></div><input type="submit" value="Send" class="btn btn-primary" id="contact-submit">
</form>
</div>
</div><!-- end add container -->
<div class="container mt-5">
<h2>Table information of Contacts (<span id="total-contacts"></span>)</h2>
<table class="table" id="contact-list">
<thead>
<th>Name</th>
<th>Student ID</th>
<th>Student Mentor</th>
<th>Student Class</th>
<th>Email Address</th>
<th>Phone Number</th>
<th colspan="2">Actions</th>
</thead><!-- This will be filled with information later -->
<tbody></tbody>
</table>
</div><!-- Update -->
<div class="container mt-5" id="update-contact-container">
<div id="add-update-msg">
<div class="alert alert-success" role="alert">Contact record updated sucessfully</div>
</div>
<h4>Update Contact</h4>
<div class="form" id="update-contact">
<form id="update-contact-form">
<div class="form-group"><label for="update-contact-name">Name</label><input type="text" id="update-contact-name"
class="form-control" required></div><!-- Student ID -->
<div class="form-group"><label for="update-contact-ID-1">Student ID</label><input type="tel"
id="update-contact-ID-1" class="form-control" required></div><!-- Mentor -->
<div class="form-group"><label for="update-contact-mentor">Student Mentor</label><input type="text"
id="update-contact-mentor" class="form-control" required></div><!-- Class -->
<div class="form-group"><label for="update-contact-class">Class</label><input type="text"
id="update-contact-class" class="form-control" required></div><!-- Email -->
<div class="form-group"><label for="update-contact-email">Email</label><input type="email"
id="update-contact-email" class="form-control" required><small id="update-contact-email-help"
class="form-text text-muted">We'll never share your email with anyoneelse.</small></div><!-- Phone -->
<div class="form-group"><label for="update-contact-phone">Phone</label><input type="text"
id="update-contact-phone" class="form-control"><input type="hidden" id="update-contact-id"></div><input
type="submit" value="Update Contact Details" class="btn btn-warning" id="update-contact-submit">
</form>
</div>
</div><!-- DELETE -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.1.3/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js"
integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>

变量id在事件处理程序函数的上下文中确实是未定义的。我们需要从别的地方得到信息。

由于删除操作是由点击#contact-list中的.delete元素触发的,因此您应该直接从该元素中删除id。事实上,它可以在那里找到:

<a href='' class='delete' data-id='${response[i]._id}'>Del</a>

data-id保存之前从AJAX服务器接收到的id。可以通过查看被单击的元素e.target.dataset.id属性来引用它。所以,你的.on("click", ".delete", function (e) {...}应该看起来像这样:

$("#contact-list").on("click", ".delete", function (e) {
e.preventDefault();
if (confirm("Do you want to delete this item?")){
var settings = {
"async": true,
"crossDomain": true,
"url": `https://example-95e6.restdb.io/rest/studentcrud/${e.target.dataset.id}`,
"method": "DELETE", // delete based on ID
"headers": {
"content-type": "application/json",
"x-apikey": APIKEY,
"cache-control": "no-cache"
}        
$.ajax(settings).done(function (response) {
console.log(response);
//update our table 
getContacts();
});
}
})

最新更新