Ini pertama kalinya saya bekerja dengan JQuery dan Ajax, saya terjebak pada masalah ini selama beberapa jam terakhir, mencari melalui berbagai solusi serupa tetapi tidak ada yang berhasil untuk saya

Masalah

Setiap kali saya mengklik tombol "kirim" Ajax mengirimkan data ke tampilan DJango tetapi jika bagian permintaan "posting" menolak untuk dieksekusi tetapi bagian lain dijalankan tidak peduli berapa kali saya mengubah kode

HTML

<form id="login-form" class="LoginForm" action="" method="post">
    {% csrf_token %}
    <h3 class="text-center text-info">Login</h3>
    <div class="error">

    </div>
    <div class="box">
        <div class="form-group">
            <label for="username" class="text-info">Username:</label><br>
            <input type="text" name="username" id="username" class="form-control">
        </div>
        <div class="form-group">
            <label for="password" class="text-info">Password:</label><br>
            <input type="text" name="password" id="password" class="form-control">
        </div>
        <div class="form-group">
            <label for="remember-me" class="text-info"><span>Remember me</span> <span><input
                        id="remember-me" name="remember-me" type="checkbox"></span></label><br>
            <input type="submit" name="LoginButton" id="LoginButton" class="btn btn-info btn-md"
                value="submit">
        </div>
    </div>
    <div id="register-link" class="text-right">
        <a href="#" class="text-info">Register here</a>
    </div>
</form>

Naskah

$(document).ready(function () {
  $("#LoginButton").click(function () {
    var username = $("#username").val();
    var password = $("#password").val();
    if ($.trim(username).length > 0 && $.trim(password).length > 0) {
      alert("Username and password were trimmed");
      console.log("Username = " + username + "\n Password = " + password);
      $.ajax({
        url: '{% url "loginCheck" %}',
        method: "post",
        data: {
          username: username,
          password: password,
          csrfmiddlewaretoken: "{{ csrf_token }}",
        },
        cache: false,
        beforeSend: function () {
          $("#LoginButton").val("Checking...");
        },
        success: function (data) {
          console.log(data);
          var dataSet = JSON.parse(data);
          alert("Username is: " + username + " Password is: " + password);
          console.log(data.status);
          if (data.status == "ok") {
            window.location.href = "check.html";
          } else if (data.status == 0) {
            alert("Can't resolve the username and password");
            console.log(data);
          } else {
            $("#error").html('<span class="text-danger">Invalid username or password</span> ');
            $("#login-form").effect("Shake", options, 800);
          }
        },
      });
    } else {
      alert("Please enter data, Null not allowed");
    }
  });
});

View.py

def loginCheck(request):
    if request.is_ajax():
        print("AJAX sent data!!!!")
    else:
        print("DJANGO brought data!!!")

    if request.method == "post":
        print("!!!!!!!~~~~~~~~~~~~~~Executed~~~~~~~~~~~~~~!!!!!!!!")
        username = request.post.get("username")
        password = request.post.get("password")
        rePack = request.session["username"] = username
        print("Values: \n Username = " + username + " \n with session = " + rePack)

        # Validate values with database here

        return JsonResponse({"status": "ok"})
    else:
        print("\n !!!~~~~Else block was executed~~~!!! \n")
        return JsonResponse({"status": 0})

Lacak balik

    [27/May/2021 18:38:40] "POST /loginCheck HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 51188)
Traceback (most recent call last):
  File "Python36-32\lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "Python36-32\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "Python36-32\lib\wsgiref\handlers.py", line 332, in send_headers
    self.send_preamble()
  File "Python36-32\lib\wsgiref\handlers.py", line 255, in send_preamble
    ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')
  File "Python36-32\lib\wsgiref\handlers.py", line 453, in _write
    result = self.stdout.write(data)
  File "Python36-32\lib\socketserver.py", line 775, in write
    self._sock.sendall(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Python36-32\lib\wsgiref\handlers.py", line 141, in run
    self.handle_error()
  File "Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 119, in handle_error
    super().handle_error()
  File "Python36-32\lib\wsgiref\handlers.py", line 368, in handle_error
    self.finish_response()
  File "Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response
    self.write(data)
  File "Python36-32\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "Python36-32\lib\wsgiref\handlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "Python36-32\lib\wsgiref\handlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Python36-32\lib\socketserver.py", line 639, in process_request_thread
    self.finish_request(request, client_address)
  File "Python36-32\lib\socketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "Python36-32\lib\socketserver.py", line 696, in __init__
    self.handle()
  File "Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle
    self.handle_one_request()
  File "Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 197, in handle_one_request
    handler.run(self.server.get_app())
  File "Python36-32\lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "Python36-32\lib\site-packages\django\core\servers\basehttp.py", line 114, in close
    super().close()
  File "Python36-32\lib\wsgiref\simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

Beberapa hal yang saya coba untuk menyelesaikan masalah:

  1. Saya mencoba mengubah "metode" ajax menjadi "ketik" tetapi itu mengembalikan kesalahan "pemisahan" objek "NonType"
  2. Saya mencoba mengubah browser ke Brave dari Firefox karena Firefox terus memutuskan koneksi pada mesin Host (itulah yang dikatakan kesalahannya) tetapi berfungsi dengan baik pada berani
  3. Saya mencoba mencetak nama pengguna dan kata sandi di konsol (berani), tetapi anehnya itu menunjukkan nama pengguna dan kata sandi tetapi berkedip dan menghilang
  4. Saya mencoba menghapus validator metode "posting" tetapi mengembalikan kesalahan "NonType" di terminal
  5. Mengubah metode menjadi "mendapatkan" alih-alih "memposting" saya dapat melihat url di terminal VSC tetapi hanya itu saja

Sunting: versi python = 3.6.5 versi Django = 3.1.2

Sunting 2: menambahkan Traceback

0
MJShinichi 27 Mei 2021, 15:41

1 menjawab

Jawaban Terbaik

Django

request.method selalu di atas- kasus.

Kamu akan membutuhkan

if request.method == "POST":

Dalam pandangan Anda.

(Di masa depan, Anda dapat melakukan sedikit debug cetak: a print(request.method) dalam tampilan Anda dan melihat konsol Django akan memecahkan ini untuk Anda.)

Paling depan

Karena Anda melakukan POSTing dengan AJAX pada tombol kirim, Anda juga perlu mencegah tindakan pengiriman default. Jika tidak, browser Anda juga akan menavigasi ke halaman lain.

Belok

$("#LoginButton").click(function () {

Ke

$("#LoginButton").click(function (event) {
  event.preventDefault();

Untuk mencegah tindakan default.

2
AKX 27 Mei 2021, 13:21