request.is_ajax()在Django中返回FALSE。无法找出原因

时间:2019-05-21 10:54:56

标签: ajax django

作为一个测试,我正在尝试在我的项目中实现AJAX功能,以首先掌握技术。

我有以下观点:


class ContactAjax(View):
    form_class = ContactForm
    template_name = "testapp/contact.html"

    def get(self, *args, **kwargs):
        form = self.form_class()
        return render(self.request, self.template_name, {"contactForm": form})

    def post(self, *args, **kwargs):

        if self.request.method == "POST" and self.request.is_ajax():
            form = self.form_class(self.request.POST)
            form.save()
            return JsonResponse({"success": True}, status=200)
        else:
            if self.request.is_ajax():
                return JsonResponse({"NO success": "  ajax"},  status=400, safe=False)
            else:
                return JsonResponse({"NO success": "no ajax"}, status=400, safe=False)

除self.request.is_ajax()以外的所有作品:始终返回False。 我在这里Django request.is_ajax returning false已读过,HTTP_X_REQUESTED_WITH应该出现在标题中。我已经用whiteshark检查了它,似乎它不在其中(日志位于正文的结尾)。 我对JS的了解几乎为零,我希望自己弄乱了脚本本身,因此我没有HTTP_X_REQUESTED_WITH。

能否请您检查一下并说出是否错误以及我是否因为脚本或其他原因而没有收到HTTP_X_REQUESTED_WITH?或者因为我完全错误地使用了perhsps?


<!-- templates/testapp/contact.html  -->

{% extends "base.html" %}
{% load bootstrap4 %}
{% bootstrap_jquery "full" %}
{% block head %}
    <title>Contact Form[FBV]</title>
{% endblock %}
{% block style %}
{% endblock %}
{% block content %}
<div class="container">
   <div class="jumbotron">
      <h1 class="text-center display-4">Contact Form[FBV]</h1>
      <p class="lead text-center">This is sample example for integration of AJAX with Django</p>
    </div>
    <div class="row justify-content-center align-items-center">
      <div class="col-sm-6 ">
        <form id = "contactForm" method= "POST">
            {% csrf_token %}
            {{ contactForm.as_p }}
            <input type="submit" name="contact-submit" class="btn btn-primary" />
        </form>
      </div>
   </div>
</div>
{% endblock %}
{% block script %}
<script type="text/javascript">
$(document).ready(function(){
   $("#contactForm").submit(function(e){
    // prevent from normal form behaviour
        e.preventDefault();
        // serialize the form data
        var serializedData = $(this).serialize();
        $.ajax({
            type : 'POST',
            url :  "{% url "testapp:contact_submit_cbw" %}",
            data : serializedData,
            success : function(response){
            //reset the form after successful submit
                $("#contactForm")[0].reset();
            },
            error : function(response){
                console.log(response)
            }
        });
   });
});
</script>
{% endblock %}


Whiteshark中的请求/响应对


78  6.231936    127.0.0.1   127.0.0.1   HTTP    1228    POST /test/cbw/ HTTP/1.1  (application/x-www-form-urlencoded)


Frame 78: 1228 bytes on wire (9824 bits), 1228 bytes captured (9824 bits) on interface 0
    Interface id: 0 (\Device\NPF_{27A91F52-F380-4B4A-8653-CAEC1E4A1180})
    Encapsulation type: NULL/Loopback (15)
    Arrival Time: May 21, 2019 13:37:30.616443000 RTZ 2 (зима)
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1558435050.616443000 seconds
    [Time delta from previous captured frame: 0.022416000 seconds]
    [Time delta from previous displayed frame: 0.000000000 seconds]
    [Time since reference or first frame: 6.231936000 seconds]
    Frame Number: 78
    Frame Length: 1228 bytes (9824 bits)
    Capture Length: 1228 bytes (9824 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: null:ip:tcp:http:urlencoded-form]
    [Coloring Rule Name: HTTP]
    [Coloring Rule String: http || tcp.port == 80 || http2]
Null/Loopback
    Family: IP (2)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
    0100 .... = Version: 4
    .... 0101 = Header Length: 20 bytes (5)
    Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT)
    Total Length: 1224
    Identification: 0x4c1a (19482)
    Flags: 0x4000, Don't fragment
    Time to live: 128
    Protocol: TCP (6)
    Header checksum: 0x0000 [validation disabled]
    [Header checksum status: Unverified]
    Source: 127.0.0.1
    Destination: 127.0.0.1
Transmission Control Protocol, Src Port: 62112, Dst Port: 8000, Seq: 1, Ack: 1, Len: 1184
    Source Port: 62112
    Destination Port: 8000
    [Stream index: 13]
    [TCP Segment Len: 1184]
    Sequence number: 1    (relative sequence number)
    [Next sequence number: 1185    (relative sequence number)]
    Acknowledgment number: 1    (relative ack number)
    0101 .... = Header Length: 20 bytes (5)
    Flags: 0x018 (PSH, ACK)
        000. .... .... = Reserved: Not set
        ...0 .... .... = Nonce: Not set
        .... 0... .... = Congestion Window Reduced (CWR): Not set
        .... .0.. .... = ECN-Echo: Not set
        .... ..0. .... = Urgent: Not set
        .... ...1 .... = Acknowledgment: Set
        .... .... 1... = Push: Set
        .... .... .0.. = Reset: Not set
        .... .... ..0. = Syn: Not set
        .... .... ...0 = Fin: Not set
        [TCP Flags: ·······AP···]
    Window size value: 10173
    [Calculated window size: 10173]
    [Window size scaling factor: -1 (unknown)]
    Checksum: 0x3ad1 [unverified]
    [Checksum Status: Unverified]
    Urgent pointer: 0
    [SEQ/ACK analysis]
        [Bytes in flight: 1184]
        [Bytes sent since last PSH flag: 1184]
    [Timestamps]
    TCP payload (1184 bytes)
Hypertext Transfer Protocol
    POST /test/cbw/ HTTP/1.1\r\n
    Host: 127.0.0.1:8000\r\n
    Connection: keep-alive\r\n
    Content-Length: 219\r\n
        [Content length: 219]
    Cache-Control: max-age=0\r\n
    Origin: http://127.0.0.1:8000\r\n
    Upgrade-Insecure-Requests: 1\r\n
    DNT: 1\r\n
    Content-Type: application/x-www-form-urlencoded\r\n
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.132\r\n
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
    Referer: http://127.0.0.1:8000/test/cbw/\r\n
    Accept-Encoding: gzip, deflate, br\r\n
    Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\r\n
     [truncated]Cookie: PGADMIN_LANGUAGE=en; PGADMIN_KEY=0cd6cd52-e769-4a53-9156-8414410647c1; time=title; mark=descending; django_language=en; ordering=boat_length; djdttop=31; csrftoken=dJA7jTyz5RPAW1UGaJkgHwyzHJRPF0gRIqTQRnTZG5e6YZBZplldqo
        Cookie pair: PGADMIN_LANGUAGE=en
        Cookie pair: PGADMIN_KEY=0cd6cd52-e769-4a53-9156-8414410647c1
        Cookie pair: time=title
        Cookie pair: mark=descending
        Cookie pair: django_language=en
        Cookie pair: ordering=boat_length
        Cookie pair: djdttop=31
        Cookie pair: csrftoken=dJA7jTyz5RPAW1UGaJkgHwyzHJRPF0gRIqTQRnTZG5e6YZBZplldqovTBR1feq2i
        Cookie pair: sessionid=j65aloh0l97i9g454vcf5h3kubdd1izz
        Cookie pair: djdtTimerPanel=on
        Cookie pair: djdtRedirectsPanel=on
        Cookie pair: djdt=hide
    X-Compress: null\r\n
    \r\n
    [Full request URI: http://127.0.0.1:8000/test/cbw/]
    [HTTP request 1/1]
    [Response in frame: 110]
    File Data: 219 bytes
HTML Form URL Encoded: application/x-www-form-urlencoded




110 6.373872    127.0.0.1   127.0.0.1   HTTP    69  HTTP/1.1 400 Bad Request  (application/json)

Frame 110: 69 bytes on wire (552 bits), 69 bytes captured (552 bits) on interface 0
    Interface id: 0 (\Device\NPF_{27A91F52-F380-4B4A-8653-CAEC1E4A1180})
    Encapsulation type: NULL/Loopback (15)
    Arrival Time: May 21, 2019 13:37:30.758379000 RTZ 2 (зима)
    [Time shift for this packet: 0.000000000 seconds]
    Epoch Time: 1558435050.758379000 seconds
    [Time delta from previous captured frame: 0.000014000 seconds]
    [Time delta from previous displayed frame: 0.141936000 seconds]
    [Time since reference or first frame: 6.373872000 seconds]
    Frame Number: 110
    Frame Length: 69 bytes (552 bits)
    Capture Length: 69 bytes (552 bits)
    [Frame is marked: False]
    [Frame is ignored: False]
    [Protocols in frame: null:ip:tcp:http:json]
    [Coloring Rule Name: HTTP]
    [Coloring Rule String: http || tcp.port == 80 || http2]
Null/Loopback
    Family: IP (2)
Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
    0100 .... = Version: 4
    .... 0101 = Header Length: 20 bytes (5)
    Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT)
    Total Length: 65
    Identification: 0x4c24 (19492)
    Flags: 0x4000, Don't fragment
    Time to live: 128
    Protocol: TCP (6)
    Header checksum: 0x0000 [validation disabled]
    [Header checksum status: Unverified]
    Source: 127.0.0.1
    Destination: 127.0.0.1
Transmission Control Protocol, Src Port: 8000, Dst Port: 62112, Seq: 241, Ack: 1185, Len: 25
    Source Port: 8000
    Destination Port: 62112
    [Stream index: 13]
    [TCP Segment Len: 25]
    Sequence number: 241    (relative sequence number)
    [Next sequence number: 266    (relative sequence number)]
    Acknowledgment number: 1185    (relative ack number)
    0101 .... = Header Length: 20 bytes (5)
    Flags: 0x018 (PSH, ACK)
        000. .... .... = Reserved: Not set
        ...0 .... .... = Nonce: Not set
        .... 0... .... = Congestion Window Reduced (CWR): Not set
        .... .0.. .... = ECN-Echo: Not set
        .... ..0. .... = Urgent: Not set
        .... ...1 .... = Acknowledgment: Set
        .... .... 1... = Push: Set
        .... .... .0.. = Reset: Not set
        .... .... ..0. = Syn: Not set
        .... .... ...0 = Fin: Not set
        [TCP Flags: ·······AP···]
    Window size value: 10228
    [Calculated window size: 10228]
    [Window size scaling factor: -1 (unknown)]
    Checksum: 0x1da3 [unverified]
    [Checksum Status: Unverified]
    Urgent pointer: 0
    [SEQ/ACK analysis]
        [Bytes in flight: 25]
        [Bytes sent since last PSH flag: 25]
    [Timestamps]
    TCP payload (25 bytes)
    TCP segment data (25 bytes)
[5 Reassembled TCP Segments (265 bytes): #102(26), #104(37), #106(38), #108(139), #110(25)]
    [Frame: 102, payload: 0-25 (26 bytes)]
    [Frame: 104, payload: 26-62 (37 bytes)]
    [Frame: 106, payload: 63-100 (38 bytes)]
    [Frame: 108, payload: 101-239 (139 bytes)]
    [Frame: 110, payload: 240-264 (25 bytes)]
    [Segment count: 5]
    [Reassembled TCP length: 265]
    [Reassembled TCP Data: 485454502f312e3120343030204261642052657175657374…]
Hypertext Transfer Protocol
    HTTP/1.1 400 Bad Request\r\n
    Date: Tue, 21 May 2019 10:37:30 GMT\r\n
    Server: WSGIServer/0.2 CPython/3.7.2\r\n
    Content-Type: application/json\r\n
    X-Frame-Options: SAMEORIGIN\r\n
    Content-Length: 25\r\n
        [Content length: 25]
    Vary: Accept-Language, Cookie\r\n
    Content-Language: en-us\r\n
    \r\n
    [HTTP response 1/1]
    [Time since request: 0.141936000 seconds]
    [Request in frame: 78]
    [Request URI: http://127.0.0.1:8000/test/cbw/]
    File Data: 25 bytes
JavaScript Object Notation: application/json
    Object

我也通过渲染检查了META

 HttpResponse(  self.request.META)

那里也没有

0 个答案:

没有答案