【问题标题】:How can we pass element ID as a variable in an AJAX request?我们如何在 AJAX 请求中将元素 ID 作为变量传递?
【发布时间】:2021-09-25 18:31:54
【问题描述】:

我正在尝试编写一个模板来创建博客提要,例如具有多个同类实例的博客网站。 现在,每个实例(每个博客文章)都需要自己的点赞按钮。为了实现这个特性,我使用了 AJAX。 我可以通过单击“关注”按钮在数据库中进行更改,但无法使用成功功能在模板中进行更改。 这是模板,

    {% for question, count, is_follow in zipp %}

<div class="border rounded my-2 px-3 py-1" style="box-shadow: 2px 2px 5px #2b6dad;">

<p class="fst-normal">
  <small>Tags: </small>
  {% for tag in question.tags.all %}
    <small><a href="{% url 'tag' tag.slug %}" style="text-decoration:none; color:black"><i>{{tag.name}} |</i></a></small>
  {% endfor %}
</p>

<p><a href="{{question.get_absolute_url}}" style="text-decoration: none; color: black"><h5>{{ question.question }}</h5>
<small>Arguments added: {{ count }}</small></a></p>
<div class="blank" id="{{question.question_id}}">
  {% include 'snippets/follow_question.html' %}
</div>
<button type="button" class="btn btn-secondary btn-sm mt-1"><i class="fa fa-share-alt" style="padding-right: 3px;"></i>Share</button>
</div>

{% endfor%}

脚本

<script type='text/javascript'>

$(document).ready(function(event){
  $(document).on('click', '#follow', function(event){
    event.preventDefault();
    var pk = $(this).attr('value');
    $.ajax({
      type: 'POST',
      url: '{% url 'follow_question' %}',
      data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
      datatype: 'json',
      success: function(response){
        var id = $(this).closest('.blank').data('id');
        $(id).html(response['form']);
      },
      error: function(rs, e){
        console.log(rs.responseText);
      },
    });
  });
});

</script>

据我了解,问题出在成功功能上。我正在尝试在正确的实例中进行更改。我从这个问题中得到了这个想法 Question

follow_question.html

<div class='d-flex flex-row'>
<form action = "{% url 'follow_question' %}" method = "post">{% csrf_token %}
  {% if is_follow %}
    <button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Followed</button>
  {% else %}
    <button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Follow</button>
  {% endif %}
</form>

Views.py

def follow_question(request):
question = get_object_or_404(Question, question_id = request.POST.get("id"))

is_follow = False

if question.follow.filter(username = request.user).exists():
    question.follow.remove(request.user)
    is_follow = False
else:
    question.follow.add(request.user)
    is_follow = True

context = {}
context["question"] = question
context["is_follow"] = is_follow

if request.is_ajax():
    html = render_to_string('snippets/follow_question.html', context, request=request)
    return JsonResponse({'form':html})

【问题讨论】:

  • is_follow 是一个布尔字段?
  • 是的,is_follow 是一个布尔字段。

标签: javascript jquery django ajax


【解决方案1】:

如果您的 is_follow 是一个布尔字段,您必须这样做

{% if is_follow %}
    <button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Followed</button>
  {% else %}
    <button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Follow</button>
  {% endif %}

如果您使用 GET 请求执行此操作,则不必将其添加到表单标记中可以用 POST

改变它

在你的 Ajax 中这样做

$(document).ready(function(){ // you don't need to pass a event on document ready
  $(document).on('click', '#follow', function(event){
    event.preventDefault();
    var pk = $(this).attr('value');
    $.ajax({
      type: 'GET',
      url: '{% url 'follow_question' %}',
      data: {'id': pk},
      datatype: 'json',
      success: function(response){
        // here you have to do nothing or you can just pass a success msg button is automatically changed by Django template
      },
      error: function(rs, e){
        console.log(rs.responseText);
      },
    });
  });
});

在你的视野中你可以这样做

def my_ajax_call(request):
    if request.method == 'GET' and request.is_ajax():
       id = request.GET.get('id')
       Mymodel.objects.filter(id=id).update(is_follow=True) 
       # or you can check the value of is_follow by sending it from ajax call 
       to your view and can add toggle condition like this 

def my_ajax_call(request):
    if request.method == 'GET' and request.is_ajax():
       follow_status = request.GET.get('is_follow')
       id = request.GET.get('id')
       if follow_status:
         follow_status = False
       else:
         follow_status = True
       Mymodel.objects.filter(id=id).update(is_follow=follow_status)  

 

【讨论】:

  • 我删除了表单标签,因为它是多余的。但主要问题仍然存在。我能够更改数据库中的状态。我无法做的是在模板中将按钮从“关注”更改为“关注”。我也在问题中包含了这个观点。请看一看。
  • 尝试在 if 和 else 之前设置 is_follow = '' 而不是 is_follow = False
【解决方案2】:

您可以将 $(this) 定义为变量并在其他地方使用它,尤其是在 ajax 事件函数中:

<script type='text/javascript'>
    
    $(document).ready(function(event){
      $(document).on('click', '#follow', function(event){
        event.preventDefault();
        var this_element = $(this) // HERE
        var pk = $(this_element).attr('value'); // HERE
        $.ajax({
          type: 'POST',
          url: '{% url 'follow_question' %}',
          data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
          datatype: 'json',
          success: function(response){
            var id = $(this_element).closest('.blank').data('id');
            $(id).html(response['form']); // HERE
          },
          error: function(rs, e){
            console.log(rs.responseText);
          },
        });
      });
    });
    
    </script>

【讨论】:

  • 我进行了更改,但仍然无法正常工作。我可以更改数据库中的状态,但无法将模板中的按钮从“关注”更改为“关注”。
猜你喜欢
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 2019-04-23
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
相关资源
最近更新 更多