【发布时间】:2021-01-05 04:15:33
【问题描述】:
我正在使用 Django 进行一个小项目,其中有一个部分需要使用 Ajax jQuery。
不幸的是,我不了解 JavaScript,而且它还是库。如果您能帮助我,我将不胜感激。
我想制作关注和取消关注按钮。
但是有一个问题:我用 VAR 做了一个变量,但它没有识别并告诉我需要使用 LET。
另外,我已经定义了 URL 和一些等等,它也无法识别。
添加到那个;我有两个变量,有两个不同的名字,但只有一个路径,但它似乎也是错误的。
JavaScript 代码:
$('#following-btn').click(function() {
let user_id = $('#following-btn').attr('data-id')
let follow = $('#following-btn').text();
if (follow === 'follow') {
let url = '/account/follow/'
let btn_text = 'unfollow'
let btn_class = 'btn btn-warning text-center mx-auto'
} else {
let url = '/account/unfollow/'
let btn_text = 'follow'
let btn_class = 'btn btn-primary text-center mx-auto'
}
$.ajax({
url: url,
method:'POST',
data:{'user.id':user_id,},
success:function (data) {
if (data['status'] === 'ok'){
$('#following-btn').text(btn_text)
$('#following-btn').attr({class: btn_class})
}
}
}
)
})
视图和路径:
{% if request.user.id != user.id and not is_following %}
<button id="following-btn" data-id="{{ user.id }}" style="display: block" class="btn btn-primary text-center mx-auto"> Follow</button>
{% elif request.user.id != user.id and is_following %}
<button id="following-btn" data-id="{{ user.id }}" style="display: block" class="btn btn-warning text-center mx-auto"> Unfollow</button>
{% endif %}
问题:
【问题讨论】:
-
我发现了几个问题: - 您从 ID 为“following-btn”的按钮获取文本。此文本是“关注”或“取消关注”,但在您检查时绝不是“关注”。 - 在您的许多陈述之后,您都缺少分号。从第一个开始。确保以分号结束每个语句。 - 您多次定义变量:我建议使用默认情况,并且仅在不是您的默认情况时重新分配变量。
-
@AnnaM:谢谢你,安娜,你的回复。我在一段视频中观看了这段代码,然后用 LET 代替了 VAR 和……最后为他工作。正如我之前所说,我对JQuery一无所知,我认为代码的格式就在这里,但是由于JavaScript更新,如果您知道我将如何感激我,我需要更改其中的一些。
标签: javascript python python-3.x django ajax