gpt4 book ai didi

javascript - 展平嵌套的 ajax 请求

转载 作者:行者123 更新时间:2023-11-30 14:29:53 25 4
gpt4 key购买 nike

我打算在问题和答案的底部写一个“编辑”链接作为 stackoverflow 的链接:

我写了一个edit glyphicon并且有一个commend.id

<div class="post-menu pull-left">
<a class="editCommentLink" href="#">
<span id="{{ comment.id }}" class="glyphicon glyphicon-edit" aria-hidden="true">edit </span>
</a> &nbsp
<a class="delCommentLink" id="{{ comment.id }}" href="#">
<span id="{{ comment.id }}" class="glyphicon glyphicon-trash" aria-hidden="true">delete</span>
</a>
</div>

在javascript中,当点击编辑图标时,向url发出ajax get请求,成功后显示一个预先制定的表单;在成功范围内,
我写了另一个 ajax 来发送更新的评论,它的粗略结构很像:

<script>
$(document).ready(function () {
$(".editCommentLink").on("click", function (e) {
e.preventDefault();
//trigger to show the form template
$.ajax({
type: "GET",
url: `/article/comment/edit/${comment_id}`,
success: function (data) {
var commentEditForm = `
<form action="#" method="post"> {% csrf_token %}
<textarea></textarea>
<button class="btn btn-primary" id="editCommentBtn">Save Edits</button >
</form >`;
$commentNew.html(commentEditForm);

//submit data from the newly emerged form,
$("#editCommentBtn").on("click", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: `/article/comment/edit/${comment_id}`,
data: param,
success: function (data) {
ret = JSON.parse(data);
alert(ret['status']);
viewedComment = simplemde.options.previewRender(comment);
updatedComment = '<p>' + viewedComment + '</p>';
alert(comment)
$commentNew.html(updatedComment);
$additionalInfo.show();
},
});//post-ajax
});//submit click event
},//success
});//ajax.get
}); //edit click event
</script>

代码实现了我的意图,
但是嵌套太多了,
扁平化代码是否可以解决问题?

最佳答案

委托(delegate)您的第二个点击事件,将其移出 ajax 事件

<script>
$(document).ready(function () {
$(".editCommentLink").on("click", function (e) {
e.preventDefault();
//trigger to show the form template
$.ajax({
type: "GET",
url: `/article/comment/edit/${comment_id}`,
success: function (data) {
var commentEditForm = `
<form action="#" method="post"> {% csrf_token %}
<textarea></textarea>
<button class="btn btn-primary" id="editCommentBtn">Save Edits</button >
</form >`;
$commentNew.html(commentEditForm);
},//success
});//ajax.get
//submit data from the newly emerged form,
$("body").on("click","#editCommentBtn", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: `/article/comment/edit/${comment_id}`,
data: param,
success: function (data) {
ret = JSON.parse(data);
alert(ret['status']);
viewedComment = simplemde.options.previewRender(comment);
updatedComment = '<p>' + viewedComment + '</p>';
alert(comment)
$commentNew.html(updatedComment);
$additionalInfo.show();
},
});//post-ajax
});//submit click event
}); //edit click event
</script>

关于javascript - 展平嵌套的 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51377016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com