我正在尝试使用django视图测试ajax的使用。我是ajax和django的新手。我创建了一个3 * 3按钮单元的网格。当我单击任何按钮时,它会用'X'替换它的文本,然后在ajax的帮助下传递给查看“handler”。但是在我的情况下,它没有传递控件来查看“处理程序”。我不明白为什么它不起作用。 这是我的代码:
url file:
from django.conf.urls import include, url
from django.contrib import admin
from game import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^handler/',views.handler,name='handler'),
url(r'^$',views.home,name='home'),
]
观看档案
from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
def handler(request):
if request.is_ajax():
pos = request.POST['pos']
return HttpResponse(2)
else:
raise Http404
def home(request):
context = {}
return render(request,"game/home.html",context)
home.html文件:
<head>
<head>
<style>
td {
padding:0;
}
table {
height:240px;
width:240px;
border-collapse: collapse;
border-spacing: 0
}
input {
margin:0;
width:80px;
height:80px;
font-size: 50px;
text-align: center;
}
#content {
position:absolute;
top:210px;
left:540px;
}
</style>
<script>
function change(id)
{
var y = document.getElementById(id);
y.value = 'X';
$.ajax({
url:"handler/",
type:"POST",
data:{pos:id},
success:function(data) {
var x = document.getElementById(data);
x.value = 'O';
console.log("sucess");
},
error:function(xhr,errmsg,err) {
alert("error");
}
});
}
</script>
</head>
<body>
<div id = "content">
<center><table>
<tr>
<td><input type = "button" onclick="change(1)" id = "1"></input></td>
<td><input type = "button" onclick="change(2)" id = "2"></input></td>
<td><input type = "button" onclick="change(3)" id = "3"></input></td>
</tr>
<tr>
<td><input type = "button" onclick="change(4)" id = "4"></input></td>
<td><input type = "button" onclick="change(5)" id = "5"></input></td>
<td><input type = "button" onclick="change(6)" id = "6"></input></td>
</tr>
<tr>
<td><input type = "button" onclick="change(7)" id = "7"></input></td>
<td><input type = "button" onclick="change(8)" id = "8"></input></td>
<td><input type = "button" onclick="change(9)" id = "9"></input></td>
</tr>
</table>
</center>
</div>
</body>
</html>
答案 0 :(得分:1)
使用csrf_exempt装饰器,因为你没有通过ajax发送csrf令牌。此外,请确保已将<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
包含在模板文件中。这应该有用。
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
@csrf_exempt
def handler(request):
if request.is_ajax():
pos = request.POST['pos']
return HttpResponse(2)
else:
raise Http404