Javascript 使用AJAX从JS运行django函数
我有一个html按钮。当我按下它时,我想运行一个JS函数,该函数将调用django函数。网站加载,但当我按下按钮时,什么也没有发生。谁能看出我错在哪里 HTML:Javascript 使用AJAX从JS运行django函数,javascript,django,Javascript,Django,我有一个html按钮。当我按下它时,我想运行一个JS函数,该函数将调用django函数。网站加载,但当我按下按钮时,什么也没有发生。谁能看出我错在哪里 HTML: <input type='button' value='run function' onclick='runScript()'> path('printing_function/', views.printing_function, name='printing_function') def printing_func
<input type='button' value='run function' onclick='runScript()'>
path('printing_function/', views.printing_function, name='printing_function')
def printing_function(request):
print("hello")
return HttpResponse()
function runScript() {
$.ajax({
url: 'print_function/',
success: function(data) {
}
});
}
视图。py:
<input type='button' value='run function' onclick='runScript()'>
path('printing_function/', views.printing_function, name='printing_function')
def printing_function(request):
print("hello")
return HttpResponse()
function runScript() {
$.ajax({
url: 'print_function/',
success: function(data) {
}
});
}
Main.js:
<input type='button' value='run function' onclick='runScript()'>
path('printing_function/', views.printing_function, name='printing_function')
def printing_function(request):
print("hello")
return HttpResponse()
function runScript() {
$.ajax({
url: 'print_function/',
success: function(data) {
}
});
}
通常情况下,我会使用这样的方式:
function runScript() {
// Add a log just to see if the function works
console.log('button clicked!')
$.get("{% url 'printing_function' %}")
.done(function(response) {
console.log(response)
)
.fail(function(error) {
console.log(error)
)
}
请注意,{%url…%}
只能在HTML模板中使用。如果您在另一个文件中隔离了JS,则必须用准确的url替换它:/printing\u function/
(正如@xyres所指出的)
在我看来,我更喜欢返回一个JsonResponse
:
def printing_function(request):
print("hello")
return JsonResponse({'success': True})
这可能需要更多的调试细节。对ajax请求的响应是什么?在urls.py中,url是
printing\u function/
,而在ajax函数中,url是print\u function/
。URL不匹配。另外,在html模板中,URL的开头要用斜杠(/
),否则会遇到意想不到的麻烦。有关更多信息,请阅读相对路径和绝对路径。