Отправка данных на сервер с помощью POST с помощью AJAX

Я новичок в Django, я хочу отправить данные на сервер с помощью AJAX и POST и получить возвращаемые данные. Я знаю, что AJAX работает правильно, так как я успешно выполнял запрос GET, но когда я выполняю запрос POST, я не получаю никаких данных ответа с сервера. Заранее спасибо.

views.py

def validate_username(request):
        if request.method == "POST" and request.is_ajax():
                description = request.POST.get('the_post')
                projects = Project.objects.filter(user__id__icontains = request.user.id).filter(pro_description__icontains = description).values_list('pro_description')

                response_data = {}
                try:
                        response_data['result'] = 'Success'
                        response_data['message'] = list(projects)
                except:
                        response_data['result'] = 'Unsuccessful'
                        response_data['message'] = 'The Subprocess module did not run the script correctly.'   

                return HttpResponse(json.dumps(response_data), content_type="application/json")

index.html

{% extends 'base.html'%}

<head>
<meta charset = "utf-8">
<meta name = "viewport" content = "width = device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<!--
{% load static  %}
<link rel="stylesheet" href = "{% static 'polls/style.css'%}" type = "text/css">
-->

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<title>this is index page!!</title>
</head>

{% block body %}
<div class = "container">

<!-- <form name="search_form" action="{ url 'search' %}" -->

<div class = "pagination">
        <input type = "text" id = "talk"></input>
        <table class = "table table-hover table-dark">
                <div class="container">
                <form name="search_form" method="POST">
                {% csrf_token %}
                        <tr>
                                <td>No<input type = "text" name = "search_no" placeholder = "Search"></input></td>
                                <td>Section<input type = "text" name = "search_section" id="id_section" placeholder = "Search"></input></td>
                                <td>Project Description<input type = "text" name = "search" id="search1" placeholder = "Search"></input><button id="submit" type="submit">search</button></td>
                                <td>Project ID<input type = "text" name = "search_id" placeholder = "Search"></input></td>
                                <td>Employee Name<input type = "text" name = "search_name" placeholder = "Search"></input></td>
                                <td>Funding Year<input type = "text" name = "search_year" placeholder = "Search"></input></td>
                        </tr>
                </form>
                </div>
                {% if projects %}
                        {% for project in projects%}
                                <tr>
                                        <td> {{project.pro_no}} </td>
                                        <td scope = "row"><a href = "{% url 'emp_detail' project.id %}">{{project.pro_section}}</a></td>
                                        <td>{{project.pro_description}}</td>
                                        <td>{{project.pro_ID}}</td>
                                        <td>
                                                {% for emp in project.employee.all  %}
                                                <table>
                                                        <tr><td>{{emp.first_name}}</td></tr>
                                                </table>
                                                {% endfor  %}
                                        </td>
                                        <td>
                                                {% for emp in project.employee.all  %}
                                                <table>
                                                        <tr><td>{{emp.funding_year}}</td></tr>
                                                </table>
                                                {% endfor  %}
                                        </td>
                                </tr>
                        {% endfor %}
                {% endif %}
                <span class = "step-links">
                        {% if projects.has_previous %}
                                <i class = "fa fa-angle-double-left" style="color:black"></i>
                                <a href = "?page={{projects.previous_page_number}}">Previous</a>
                        {% endif %}
                        <span class = "current">
                                Page {{projects.number}} of {{projects.paginator.num_pages}}.
                        </span>
                        {% if projects.has_next %}
                                <i class="fa fa-angle-double-right" style="color:black"></i>
                                <a class="fa fa-angle-double-right" style="color:black" href = "?page={{projects.next_page_number}}">Next</a>
                        {% endif %}
                <span>
        </table>

        {% block javascript %}
                <script>

                        $("#submit").click(function(e)){
                                e.preventDefault();
                                $.ajax({
                                        url: '{% url "validate_username" %}',
                                        type: "POST",
                                        data: {
                                                csrfmiddlewaretoken: csrftoken,
                                                'the_post': $('#search1').val(),
                                        },
                                        success: function(json){
                                                alert(json.message);
                                        },
                                });
                        }

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

<!-- </form> -->
</div>
                <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
                <!-- <script src="{ static 'scripts/main.js'  %}"></script> -->
{% endblock %}

urls.py

url(r'^ajax/validate_username/$', views.validate_username, name = 'validate_username'),

python,ajax,django,

0

Ответов: 1


0 принят

Я думаю, данные ajax помещаются в тело запроса.

Попробуйте это, посмотрите, получаете ли вы свои данные

from django.http  import QueryDict
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def validate_username(request):
    if request.method == "POST" and request.is_ajax():
        # The body of the request is in byte form, 
        # so we decode/convert to string using utf-8 encoding
        datastring = request.body.decode("utf-8")

        # The data comes in as if it was coming 
        # from a real form i.e. each field on the model 
        # comes separated by & e.g. the_post=demo&othefield=4 etc
        # use djangos QueryDict to get a dictionary you can easily
        # work with.
        datadictionary = QueryDict(datastring)
        # retreve value like any other dictionary

        description = datadictionary.get("the_post")

        projects = Project.objects.filter(user__id__icontains = request.user.id)
                                  .filter(pro_description__icontains = description)
                                  .values_list('pro_description')

        response_data = {}
        try:
            response_data['result'] = 'Success'
            response_data['message'] = list(projects)
        except:
            response_data['result'] = 'Unsuccessful'
            response_data['message'] = 'The Subprocess module did not run the script correctly.'   

        return HttpResponse(json.dumps(response_data), content_type="application/json")

Пожалуйста, обратите внимание: я также добавил декоратор @csrf_exempt на ваш метод, чтобы отключить защиту csrf. Пожалуйста, прочитайте о том, как установить csrf на запрос ajax

питон, Аякс, Джанго,
Похожие вопросы
Яндекс.Метрика