[英]how do I call specific function in views.py through ajax call in javascript file?
In Django we map URLs to functions in views.py. 在Django中,我们将URL映射到views.py中的函数。 If we do an ajax call then we need to mention url in ajax call but that will call the function mapped to that url.
如果进行ajax调用,则需要在ajax调用中提及url,但这将调用映射到该url的函数。 I want to call specific function from views.py via ajax call?
我想通过ajax调用从views.py调用特定功能吗? What should I do so that I can call any function in views.py via AJAX call without changing url?
我应该怎么做才能在不更改URL的情况下通过AJAX调用在views.py中调用任何函数?
views.py views.py
def index(request):
codes=Code.objects.all()[:10]
context={
'name': 'KD',
'codes': codes
}
return render(request,'coding/index.html',context)
def details(request):
code=Code.objects.get(1)
context={
'code': code
}
return render(request, 'coding/details.html', context)
urls.py urls.py
from django.contrib import admin
from django.urls import path,include
from . import views
urlpatterns = [
path('',views.index, name="index" ),
path('details',views.details, name="details" ),
];
javascript javascript
<script type="text/javascript">
$(document).ready(function() {
$("#tests").submit(function(event){
event.preventDefault();
$.ajax({
type:"POST",
url:"/details/", // what changes should be done so that I can call other function in views.py?
data: {
'video': $('#tests').val()
},
success: function(){
$('#message').html("<h2>Code Submitted!</h2>")
}
});
return false;
});
});
</script>
Just wrap function call in view and use it like usual view. 只需在视图中包装函数调用,然后像平常的视图一样使用它即可。 For example, you have a function:
例如,您有一个函数:
def print_hello():
print("Hello!")
You should create view: 您应该创建视图:
def print_hello_view(request):
print_hello()
return HttpResponse(status=200)
And add it into urls: 并将其添加到URL:
path('print-hello',views.print_hello_view, name="print_hello_view"),
And in template replace ajax url by new endpoint: 并在模板中用新端点替换ajax url:
{% url 'print_hello_view' %}
If you want have possibility to choose function you should add some condition. 如果您想选择功能,则应添加一些条件。
I think what Nikitka was saying is that you can listen for the POST request in the details view and use it to run your other python function. 我认为Nikitka所说的是,您可以在详细信息视图中监听POST请求,并使用它来运行其他python函数。 Try something like the following:
尝试如下操作:
def details(request):
# Check if there was a POST request that contains the 'video' key
if 'video' in request.POST:
# Run your python script here.
code=Code.objects.get(1)
context={
'code': code
}
return render(request, 'coding/details.html', context)
For further reading I would like to recommend Vitor Freitas's blog . 为了进一步阅读,我想推荐Vitor Freitas的博客 。
I'm not sure why you would want to do this, and from a security perspective it's a bad idea. 我不确定您为什么要这样做,从安全角度来看,这是个坏主意。 Allowing access to arbitrary functions could be exploitable, so you should avoid it.
允许访问任意功能是可以利用的,因此应避免使用它。
The ajax client will need to know in advance the names of the internal functions so that it can invoke them, and possibly also know what arguments can be passed to the function. Ajax客户端将需要事先知道内部函数的名称,以便它可以调用它们,并且还可能知道可以将哪些参数传递给该函数。 If the client has that information, then you might as well explicitly expose the functions in
urls.py
and leave it at that. 如果客户端具有该信息,那么您最好在
urls.py
显式公开这些函数,然后将其保留。
Having made my objection, you could implement a dispatch view function that accepts the request and delegates to a function specified in the request using globals()['function_name']
. 提出反对后,您可以实现一个接受视图的派发视图函数,并使用
globals()['function_name']
委托给请求中指定globals()['function_name']
。
Assuming that the functions to be called are view functions that return an appropriate value (rendered HttpResponse
, JSON, etc.) your view might look like this: 假设要调用的函数是返回适当值(渲染的
HttpResponse
,JSON等)的视图函数,则视图可能如下所示:
def call_named_function(request, function_name):
try:
return globals()[function_name](request)
except KeyError:
return JsonResponse({'error': True, 'message': 'Function {!r} not found'.format(function_name)}, status=404)
except Exception, exc:
return JsonResponse({'error': True, 'message': 'Exception calling function {!r}: {}'.format(function_name, exc)}, status=500)
Add a route to urls.py
to capture the function name and call the view function: 向
urls.py
添加路由以捕获函数名称并调用view函数:
path('call/<function_name>', views.call_named_function, name='call'),
Now you can add view functions to your code, or import them from another module, and call them using the function name appended to the URL: 现在,您可以将视图函数添加到代码中,或从另一个模块导入视图函数,然后使用附加到URL的函数名称来调用它们:
http://127.0.0.1:8000/call/function_1
http://127.0.0.1:8000/call/some_function
etc. 等等
I think that it's easier to use the above, but if you do not want to change the URL, then you will have to add something to the body of the POST request that specifies the name of the function to call: 我认为使用上面的代码更容易,但是如果您不想更改URL,则必须在POST请求的正文中添加一些内容,以指定要调用的函数的名称:
def call_named_function(request):
try:
function_name = request.POST['function_name']
return globals()[function_name](request)
except KeyError:
return JsonResponse({'error': True, 'message': 'Function {!r} not found'.format(function_name)}, status=404)
except Exception as exc:
return JsonResponse({'error': True, 'message': 'Exception calling function {!r}: {}'.format(function_name, exc)}, status=500)
with route: 与路线:
path('call', views.call_named_function, name='call'),
and POST the name of the function to call in the request with name 'function_name'
. 然后发布名称为
'function_name'
要在请求中调用'function_name'
名称。
You could also POST arguments as JSON encoded lists for positional arguments and JSON encoded dicts for keyword arguments. 您还可以将自变量作为位置参数的JSON编码列表和关键字参数的JSON编码字典进行POST。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.