如何在pythonajax中使用AJAX在点击按钮时显示/获取数据

2024-05-28 22:55:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我对ajax和django都是新手。我想从数据库中获取电话号码,并想在单击用户联系按钮时显示在模板上。但在我的情况下,我得到的第一个按钮本身,这是不正确的所有电话号码。因为不同的人有不同的电话号码。请帮帮我。提前谢谢

views.py:

from django.shortcuts import render, redirect
from .models import listing_model
from .forms import listing_form
from django.http import HttpResponse


def submissions(request):
    tasks = listing_model.objects.all()
    form = listing_form()
    if request.method =='POST':
        form = listing_form(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return redirect('submissions')
    context = {'tasks':tasks, 'form':form}
    return render(request, 'submission.html', context)

#ajax
def contact(request):
        numbers= listing_model.objects.values('phone')
        return HttpResponse( numbers )

home.html

{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Home{% endblock %}
{% block body %}
<div class="container">
<div class="row">
    <form method="GET" class="mx-auto" ><br>
    {{ user_filter.form }}<br><br>
    <button type="submit" class="btn btn-info" style="margin-left:250px">Search</button>
  </form>
</div>
</div>
<div>&nbsp; &nbsp;</div>
<div class="container">
<div class="row">
{% for task in tasks %}
<div class ="col-md-4">
<div class="card" style="width:300px">
<div class="card-body">
<h4 class="card-title">Title : {{ task.title }}</h4>
<div>Address : {{ task.address }}</div>
<div>City : {{ task.city }}</div>
<img src="{{ task.image.url }}" style="max-height:200px">
<div>&nbsp;</div>
<button class="btn btn-primary" id="request-btn">Contact</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    $("#request-btn").click(function(e){
        e.preventDefault();
        $.ajax({
            url: "/listings/contact",
            type: "GET",
            datatype:"json",
            success: function(numbers){
                alert(numbers)
}
    });
    });
}); 
</script>

</div>
</div></div>
{% endfor %}
</div></div>
{% endblock %}


Tags: djangofromimportdivformtaskrequestscript
1条回答
网友
1楼 · 发布于 2024-05-28 22:55:55
urls.py

    from django.contrib import admin
    from django.urls import path
    from ajax_with_djnago import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('listings/contact/<str:id>', views.contact),
        path('', views.home)

]


views.py

    from django.shortcuts import render
    
    from .models import listing_model
    from django.http import JsonResponse
    
    
    def home(request):
        all_detail = listing_model.objects.all()
        print(all_detail)
        return render(request, 'index.html', context={'tasks': all_detail})
    
    
    # ajax
    def contact(request, id):
        numbers = listing_model.objects.get(id=id)
        return JsonResponse({'numbers': numbers.phone}

)

models.py


    from django.db import models
    
    
    # Create your models here.
    class listing_model(models.Model):
        title = models.CharField(max_length=200, blank=True)
        address = models.CharField(max_length=200)
        city = models.CharField(max_length=200)
        image = models.ImageField(upload_to='images', blank=True)
        phone = models.IntegerField()
    
        def __str__(self):
            return self.title


index.html


    <div class="container">
        <div class="row">
            {% for task in tasks %}
                <div class="col-md-4">
                    <div class="card" style="width:300px">
                        <div class="card-body">
                            {% for task in tasks %}
                                <h4 class="card-title">Title : {{ task.title }}</h4>
                                <div>Address : {{ task.address }}</div>
                                <div>City : {{ task.city }}</div>
                                <div>&nbsp;</div>
                                <button class="btn btn-primary"
                                        id={{ task.id }} onclick="showPopup('{{ task.id }}')">Contact
                                </button>
                                <p id="contact"></p>
                            {% endfor %}
                            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
                            <script type="text/javascript">
                                function showPopup(id) {
                                    $.ajax({
                                        url: "/listings/contact/" + id,
                                        method: 'GET',
                                        headers: {'X-CSRFToken': '{{ csrf_token }}'},
                                        success: function (data) {
                                            $('#contact').html(data['numbers']);
                                        }
    
                                    });
    
                                }
                            </script>
    
                        </div>
                    </div>
                </div>
            {% endfor %}
        </div>
    </div>

For Complete Code Please check this link

相关问题 更多 >

    热门问题