我对使用 Ajax 还很陌生,但是现在已经使用 Django 一段时间了。
我想知道如何动态提交一个表单,该表单将在不刷新页面的情况下将这个新“参数”附加到 URL 并返回一些更新的数据。例如,如果我更改名为最高价格的值并单击“应用”,那么这会将“&max_price=some_new_value”添加到 URL 并返回带有最高价格过滤器的 Django 查询集。
我已经能够这样开始了......
$('.filter-ul-opt-change-apply').click(function(){
$.get(...{
...
})
})
尽管jQuery documentation指定将像 ajax/test.html 这样的 URL 作为参数传递给 get() 方法,但我不确定这将如何与 Django View 一起使用检索对象。
views.py:
def generic_view(request):
objs = Objects.objects.filter(...parameters from updated url go here...)
return render(request, 'generic-view.html', {'objs':objs})
为此目的使用 Django 和 Ajax 的任何想法都非常有用!
谢谢!
请您参考如下方法:
你可以像这样使用 ajax :
$.ajax({
type : "GET",
dataType : yourDataType,
data : {
'max_price'=some_new_value
}
url : theUrlYouMappedServerSide,
success : function(response) {
}
});
在你的 .py 中你应该有类似的东西:
from django.contrib.auth.models import User
from django.http import JsonResponse
def yourFunc(request):
max_price= request.GET.get('max_price', None)
//do some stuff
data = {
// your stuff from serverside
}
return HttpResponse(data)
你应该有一个 viewroute :
from django.conf.urls import url
from core import views
urlpatterns = [
url(r'^theUrlYouMappedServerSide/$', views.yourFunc, name='yourFunc')
]
你只需要根据你的需要使用不同于HttpResponse(data)的东西
