【问题标题】:Django Ajax: Call a specific python script within a directory of multiple python scriptDjango Ajax:在多个python脚本的目录中调用特定的python脚本
【发布时间】:2021-09-20 09:40:33
【问题描述】:

这是 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)?

【问题讨论】:

    标签: jquery django ajax django-urls


    【解决方案1】:

    为 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');
        }
    }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      相关资源
      最近更新 更多