jquery - 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)?
解决方案
为 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');
}
});
推荐阅读
- xml - 存在 xmlns 属性时如何使用 XSLT?
- c - 在 mac os x 上是否有 clang 识别的常量?
- android - 移动网络提供商阻止对 api 的 volley 请求
- reactjs - 如何在“react app 2”中设置 SCSS 文件(ViewEncapsulated 方式),如 Angular 组件特定的 SCSS?
- vue.js - 是否可以在 vueJS 中将数据从插槽组件传递到父级?
- python-3.x - 使用 GTK3 和 pycairo 的 Python3 动画
- react-native - undefined 不是评估 'this.props.dispatch 的函数
- python - 如何在没有 Pub/Sub 的情况下使用 Dataflow 将 Google Cloud Storage 存储桶流式传输到 Big Query
- excel - 无法从 url 中提取 id
- java - 将 jnetpcap 添加到 maven 失败