我想使用 Ajax 將變數從 JS 函式傳遞到我的 Django 專案中的 python 函式。我可以呼叫 python 函式。使用ajax方法,我知道這是因為python函式中的print函式運行。但是,如何通過這個 ajax 呼叫傳遞我的變數?我只想傳遞區域變數,以便它可以由 python 函式列印。
JS
function calling (){
var local = 25
$.ajax({
type:'GET',
url:'printsome/',
success: function(response){
console.log('success');
console.log(local);
},
error: function (response){
console.log('error');
}
});
}
Python
def print_some(request):
from django.http import JsonResponse
print('this python function was called')
return JsonResponse({})
uj5u.com熱心網友回復:
例如,您可以將變數作為查詢引數傳遞:
function calling (){
var local = 25
$.ajax({
type:'GET',
url:`printsome/?variable=${local}`, // <- Add the queryparameter here
success: function(response){
console.log('success');
console.log(local);
},
error: function (response){
console.log('error');
}
});
在 Django 中,您可以像下面這樣訪問查詢引數:
from django.http import JsonResponse
def print_some(request, ):
variable = request.GET.get('variable', 'default')
print('Variable:', variable)
return JsonResponse({})
在此處閱讀更多相關資訊:HttpRequest.GET
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370666.html
標籤:javascript Python 姜戈 阿贾克斯
