我正在尝试使用AJAX调用将数据发送到我的django视图,然后我希望在另一个视图中使用它。当用户点击一个特定的词时,known_words必须加一个(这部分工作)。但我也想知道用户点击了哪个词(我可以在模板中访问这个:{{item.0}}。这是我无法开始工作的部分。我的html的相关部分(这是我表的最后一列,第一列包含{{item.0}}):<a href="javascript:" class="word_known btn btn-warning btn-sm" data-word="{{item.0}}" data-songpk="{{song_pk}}" data-userpk="{{user_pk}}">Yes</a>我的js:$(document).ready(function() { var known_words = 0; var clicked_words = []; $(".word_known").click(function() { known_words++; var reference = this; var songpk = $(this).data('songpk'); var userpk = $(this).data('userpk'); var clicked_words = $(this).data('clicked_words'); //I know this part is wrong, how can I append the word to the list? $.ajax({ url: "/videos/songs/vocab/known/"+songpk+"/"+userpk+"/", data: {known_words: known_words, clicked_words: clicked_words}, success: function(result) { $(reference).removeClass("btn-warning"); $(reference).addClass("btn-success"); $(reference).text("Known"); }, failure: function(data) { alert("There is an error!") } })});})意见:def word_known(request, pk_song, pk_user): if request.method =='POST': pass elif request.method == 'GET': known_words = request.GET.get('known_words', '') clicked_words = request.GET.get('clicked_words', '') request.session['known_words'] = known_words clicked_words = [] clicked_words.append(request.session['clicked_words']) print('The number of known words is {} and clicked words are {}'.format(known_words, clicked_words)) return HttpResponse(json.dumps(known_words))在控制台中,当我单击一个单词(不是“你好”)时,我会在控制台中得到以下信息:The number of known words is 1 and clicked words are ['hello']如果我第二次点击另一个词:The number of known words is 2 and clicked words are ['hello']所以计数器正在工作,但不是单词列表。我该如何解决?
2 回答
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
我没有对此进行测试,但我认为您正在覆盖数组而不是添加到它。
这条线
var clicked_words = $(this).data('clicked_words');
应该
clicked_words.push($(this).data('clicked_words'));
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
除了@Daniel Butler 的回答,我不得不改变我的看法如下:
clicked_words = request.GET.getlist('clicked_words[]')
因为显然当您通过 jQuery 发送列表时,它也会更改关键字。
添加回答
举报
0/150
提交
取消