weixin_33699914 2015-12-04 06:23 采纳率: 0%
浏览 55

将Ajax与Django集成

I am trying to learn how to integrate ajax with django. When I click the button, the javascript function change() changes the content of the button to 'X' and then ajax is evaluated. But the control is not passed from the client to server side on button click as ajax neither returns success nor failure. It's been two days since I am stuck with ajax. Here is the full code:

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'),
]

views file:

    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 file:

<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>

Console output:

(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条回答 默认 最新

  • 程序go 2015-12-04 06:38
    关注

    You need to append a / to your url in the ajax call:

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置