在Django中未检测到Ajax Post方法

时间:2018-01-15 19:35:55

标签: javascript jquery ajax django

我正在使用Django发现Ajax并且不能让它们工作。 在继续之前,项目目录如下所示:

mySite
|
|-> myApp
    |-> views.py
    |-> urls.py
    | ... // other py-files and directories
|-> mySite
    |-> urls.py
    | ... // other py-files

当我运行站点并触发发送Ajax请求的事件时,我得到状态200代码但是views.py中的函数没有被执行,所以我假设我的urls.py没有正确配置。实现Ajax帖子的Javascript:

function sendReq(){
      console.log('AJX');
      $.ajax({
        type: 'POST',
        url: 'ajax_test',
        data:{
          name: 'AjaxReq',
          val: '...',
          csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        sucess:function(){
          console.log('SUCCES!');
        }
      });
      console.log('AJX done');
    }

myApp的urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^', views.index, name='index'),
    url(r'^ajax_test', views.ajax_test, name='ajax_test'),
]

mySite的urls.py:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^',include('myApp.urls')),
]

最后是myApp的views.py:

from django.shortcuts import render
from django.http import JsonResponse

def index(request):
    return render(request, 'myApp/index.html')

def ajax_test(request):
    if request.method == 'POST':
        name = request.POST.get('name', None)
        val = request.POST.get('val', None)
        print(name + ': ' + val)

我找到了不同的解决方案,但似乎过时了。有人可以指出如何正确链接一切? 提前致谢

1 个答案:

答案 0 :(得分:0)

问题在于myApp urls.py订单。匹配的第一条路线将运行。来自Django文档:

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

将您的第一条路线放在最后一条路线之后。