所以我遇到了使用ajax和标准html表单提交的问题(我在Django中开发,但在这种情况下这不相关)。
基本上,我有一个按钮调用浏览器的URL(class =“header-btn”) - 尽可能标准 - 我有一个js脚本将鼠标坐标保存到db(使用。 mousemove)通过ajax帖子。每当我移动鼠标时,该位置都会被发送到数据库,因此您可以看到有很多请求正在进行中。问题是当我移动我的鼠标时(所以请求不断进行)然后单击引用按钮我在服务器shell中出现此错误:
Exception happened during processing of request from ('127.0.0.1', 45187)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 582, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 126, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 640, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 693, in finish
self.wfile.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
从我在其他帖子中看到的内容(我可能是错的),这似乎是因为当按钮提交完成时仍然正在处理ajax请求,因此浏览器已经在不同的页面/网址。
我想知道如何防止这种行为。我应该从html到js脚本提交所有表单提交(通过按钮单击)吗?我完全错了,有一个很好的方法可以解决这个问题吗?
我的html和js发布在下面。
提前致谢。
HTML:
<div id="header">
<table>
<tr>
<form class="header-form" action="{% url 'home:start' %}">{% csrf_token %}
<td><button type="submit" class="header-btn"> dibbs</button></td>
</form>
</tr>
</table>
</div>
<form>
{% csrf_token %}
<div id="mouse" data-done-ref="{% url 'home:mousemove' %}"></div>
</form>
<div id="data"></div>
的javascript:
function MousePosition(x,y){
this.x = x;
this.y = y;
}
$(document).ready(function(){
var currentMousePosition = new MousePosition(0,0);
$("html").mousemove(function(event){
currentMousePosition.x = event.pageX;
currentMousePosition.y = event.pageY;
$("#data").html("( "+event.pageX+" , "+event.pageY+" )");
var data = JSON.stringify({
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
x: currentMousePosition.x,
y: currentMousePosition.y
});
$.ajax({
type: "POST",
url: "http://localhost:8000/api/v1/position/",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false
});
});
});