【发布时间】:2021-08-15 17:26:02
【问题描述】:
这是我第一次使用 JQuery 和 Ajax,过去几个小时我一直被这个问题困扰,搜索了各种类似的解决方案,但对我没有任何帮助
问题
每当我点击“提交”按钮时,Ajax 都会向 DJango 视图传递数据,但如果“发布”请求部分拒绝执行,但其他部分无论我更改多少次代码都会执行
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>
脚本
$(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})
追溯
[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'
为了解决这个问题,我尝试了几件事:
- 我尝试将 ajax 的“方法”更改为“类型”,但返回“NonType”对象“拆分”错误
- 我尝试将浏览器从 Firefox 更改为 Brave,因为 Firefox 一直在终止主机上的连接(这就是错误所说的),但它在 brave 上运行良好
- 我尝试在控制台上打印用户名和密码(勇敢),但奇怪的是它显示了用户名和密码,但它会闪烁并消失
- 我尝试删除“post”方法验证器,但它在终端中返回“NonType”错误
- 将方法更改为“get”而不是“post”,我可以在 VSC 终端上看到 url,仅此而已
编辑:python 版本 = 3.6.5 django 版本 = 3.1.2
编辑 2:添加回溯
【问题讨论】:
-
您好@MJShinichi,如果您使用 post 方法发送 ajax 请求,那么您可以尝试其中任何一种,您将收到相同的数据,或者您可以像这样同时尝试两种方法
if request.method == "POST" and request.is_ajax(): -
views.py 中的缩进是怎么回事?部分代码在函数之外
-
@Lemon.py 一开始我尝试仅使用 python 检索数据,然后我添加了 ajax,所以我想确保仅使用 ajax 发送数据,因此第一个 if request.is_ajax()跨度>