使用POST和AJAX将数据发送到服务器

时间:2018-07-30 19:34:29

标签: python ajax django

我是Django的新手,我想使用AJAX和POST将数据发送到服务器,并检索返回的数据。我知道自成功执行GET请求以来AJAX正常工作,但是当我执行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'),

1 个答案:

答案 0 :(得分: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)
        # retrieve 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保护。请阅读如何to set csrf on ajax request