私の質問は、javascript 関数から django ビューに値を渡すより良い方法は何かということです。
JavaScript 関数を介して値を取得するテンプレートがあり、その値を django ビューに渡したいと考えています。
私の質問は、javascript 関数から django ビューに値を渡すより良い方法は何かということです。
JavaScript 関数を介して値を取得するテンプレートがあり、その値を django ビューに渡したいと考えています。
質問はかなり一般的ですが、これがそれを行う1つの方法です。jQuery を使用して、次のような AJAX 呼び出しを行うことができます。
$.ajax({type: 'POST',
url: '/fetch_data/', // some data url
data: {param: 'hello', another_param: 5}, // some params
success: function (response) { // callback
if (response.result === 'OK') {
if (response.data && typeof(response.data) === 'object') {
// do something with the successful response.data
// e.g. response.data can be a JSON object
}
} else {
// handle an unsuccessful response
}
}
});
そして、あなたの Django ビューは次のようになります:
def fetch_data(request):
if request.is_ajax():
# extract your params (also, remember to validate them)
param = request.POST.get('param', None)
another_param = request.POST.get('another param', None)
# construct your JSON response by calling a data method from elsewhere
items, summary = build_my_response(param, another_param)
return JsonResponse({'result': 'OK', 'data': {'items': items, 'summary': summary}})
return HttpResponseBadRequest()
ここでは多くの詳細が明らかに省略されていますが、これをガイドラインとして使用できます。
ここで 2 つの方法: