views函数
def index8(request): user_list = UserInfo.objects.values_list('username') path = '/main8/' print(user_list) return render(request, 'index8.html',locals()) from django.http import JsonResponse def main8(request): ret = {'status':'200', 'name':None, 'path':None} print(request.POST) name = request.POST.get('name') path = request.POST.get('path') ret['name'] = 'Python15期_'+name ret['path'] = path return JsonResponse(ret)
urls文件
re_path('main8/', views.main8, name='main8'), re_path('index8/', views.index8, name='index8'),
html代码
<div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> {% for row in user_list %} <p class="id_row">{{ row.0 }}</p> <p id="{{ row.0 }}"></p> <hr> {% endfor %} </div> </div> {% csrf_token %} <script src="/static/jquery-3.1.1.js"></script> <script> $('.id_row').click(function () { $(this).siblings().css('color', ''); $(this).css('color', 'red'); let tex=$(this); var name = $(this).text(); $.ajax({ url: '{{ path }}', type: 'post', data: { name: name, path: '{{ path }}', 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val() }, success: function (data) { tex.text(data['name']); console.log(data['status']); console.log(data['name']); console.log(name); var arr = data.name.split("_"); console.log(arr); $(".id_row").each(function (i, j) { if (arr[1] == j.innerText) { console.log($(this)); } }) } }) }) </script> </div> </body>