簡體   English   中英

使用POST和AJAX將數據發送到服務器

[英]Send data to server using POST with AJAX

我是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'),

我認為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保護。 請閱讀有關如何在ajax請求上設置csrf的信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM