我想在后端调用 python 函数而不重新加载页面。 像这样:
index.html
<button name="button" onclick="run_function(param1, param2)">Run</button>
views.py
some_function(param1, param2):
return(param1, param2)
请不要回答“努力学习整个 django 文档!”我已经做了一些研究,但是我还没有找到适合我的案例的任何工作代码。
最佳答案
所以最后我自己解决了这个问题。 This帮助很大。
index.html
<button name="button" onclick="run_function(param1, param2)">Run</button>
script.js
function run_function(param1, param2){
console.log("running");
$.ajax({
url : "random_url/", // the endpoint
type : "GET", // http method
data : { param_first : param1,
param_second : param2 }, // data sent with the get request
// handle a successful response
success : function(json) {
console.log("success"); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
views.py
from django.http import HttpResponse
import json
def some_func(request):
if request.method == 'GET':
param1 = request.GET.get('param_first')
param2 = request.GET.get('param_second')
print(param1, param2)
response_data = 'successful!'
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
urls.py(不知道这一步是否有必要)
urlpatterns = [
path('admin/', admin.site.urls),
path('random_url/', some_func)
]
还要确保您获得未压缩的 jquery 包。
关于python - Django 。如何从 HTML 按钮调用 python 函数而不重新加载页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59140343/