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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题