将ajax与django集成

时间:2015-12-04 06:23:11

标签: javascript jquery ajax django

我正在尝试学习如何将ajax与django集成。当我点击按钮时,javascript函数change()会将按钮的内容更改为' X'然后评估ajax。但是按钮点击时控件不会从客户端传递到服务器端,因为ajax既不会返回成功也不会失败。我被困在ajax已经两天了。 这是完整的代码:

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.index,name='index'),
    url(r'^$',views.home,name='home'),
]

观看档案:

    from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def index(request):
    print "xyx"
    if request.method == 'POST':
        return HttpResponse("sucess")
    else:
        return HttpResponse("failure")
@csrf_exempt
def home(request):
    context = {}
    return render(request,"game/home.html",context)

home.html文件:

<head>
<head>
<script>
function change()
{   
    var y = document.getElementById("one");
    y.value = 'X';
    $.ajax({
        url:"127.0.0.1:8000/handler/",
        type:"POST",
        data:{},
        cache:false,
        success:function(data) {
            var x = document.getElementById(data);
            x.value = 'O';
            alert("sucess");
        },
        error:function(error) {
            alert(error);
        }
    });
}
</script>
</head>
<body>
<input type = "button" id = "one" onclick="change()"></input>
</body>
</html>

控制台输出:

(django)shivam@shivam-HP-Pavilion-15-Notebook-PC:~/Python/django/django/django_test$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
December 05, 2015 - 18:48:10
Django version 1.9, using settings 'django_test.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[05/Dec/2015 18:48:16] "GET / HTTP/1.1" 200 453

2 个答案:

答案 0 :(得分:1)

你的函数index并不会返回任何http响应。在print返回JsonResponse之后。此外,所有帖子调用必须以尾部斜杠结尾。如果您遇到与客户端相关的任何此类问题,请检查控制台,您将找到原因。

编辑:

问题是你没有在你的html中包含jquery。我已经包含了jquery,而不是绝对的url,我使用了相对的url。唯一的问题仍然是没有标识为data的元素。解决这个问题,你会很高兴。 :)

<head>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
function change()
{   
    var y = document.getElementById("one");
    y.value = 'X';
    $.ajax({
        url:"/handler/",
        type:"POST",
        data:{},
        cache:false,
        success:function(data) {
            var x = document.getElementById(data);
            x.value = 'O';
            alert("sucess");
        },
        error:function(error) {
            alert(error);
        }
    });
}
</script>
</head>
<body>
<input type = "button" id = "one" onclick="change()"></input>
</body>
</html>

答案 1 :(得分:0)

您需要在ajax调用中将/附加到您的网址:

$.ajax({
    url:"127.0.0.1:8000/handler/",
    type:"POST",
    data:{},
    . . .