首页 > 解决方案 > Django Ajax:在多个python脚本的目录中调用特定的python脚本

问题描述

这是 urls.py 中的代码:

from djangotest.ajax.ajax_test import ajaxTest
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('', handlerView),
path('ajax/', ajaxTest)]

这是 ajax 文件夹下名为 ajax_test 的 python 脚本中的代码:

from django.shortcuts import HttpResponse
def ajaxTest(request):
    return HttpResponse("Hello World")

这是javascript:

$.ajax({
    url: 'ajax/',
    type: 'get', 
    success: function(data) {
        alert(data);
    },
    failure: function(data) { 
        alert('Encountered an error');
    }
}); 

当我运行服务器时,站点会提示“Hello World”,这意味着代码是正确的。现在,我的问题是:假设我将在名为 greetings(.py) 的 ajax 文件夹中添加另一个 python 脚本,其函数 Greet 返回“Good day!”。如何指定 ajax 调用哪个 python 脚本(例如,greetings.py)?

标签: jquerydjangoajaxdjango-urls

解决方案


为 ajax_test 文件中的每个函数创建一个单独的 URL,并在点击该 URL 时调用该函数。

from djangotest.ajax.ajax_test import ajaxTest, greetingTest
from django.contrib import admin
from django.urls import path

urlpatterns = [
      path('admin/', admin.site.urls),
      path('', handlerView),
      path('ajax/hello_word', ajaxTest)
      path('ajax/greet', greetingTest)
    ]

ajax_test 中的函数:

from django.shortcuts import HttpResponse
def greetingTest(request):
    return HttpResponse("Good day!")

从 JS 调用:

$.ajax({
    url: 'ajax/hello_world',
    type: 'get', 
    success: function(data) {
        alert(data);
    },
    failure: function(data) { 
        alert('Encountered an error');
    }
});

$.ajax({
    url: 'ajax/greet',
    type: 'get', 
    success: function(data) {
        alert(data);
    },
    failure: function(data) { 
        alert('Encountered an error');
    }
}); 

推荐阅读