我想在点击页面底部时从数据库中检索数据。
现在,到目前为止我所拥有的:
urls.py
urlpatterns = [
url(r'^$', feedViews.index, name='index'),
url(r'^load/$', feedViews.load, name='load'),
]
views.py
def index(request):
if request.method == 'GET':
context = {
'entry_list': Entry.objects.filter()[:5],
}
return render(request,'index.html',context)
else:
return HttpResponse("Request method is not a GET")
def load(request):
if request.method == 'GET':
context = {
'entry_list': Entry.objects.filter()[:1],
}
return render(request,'index.html',context)
else:
return HttpResponse("Request method is not a GET")
index.html
...
<script>
$(window).on("scroll", function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
console.log( "TEST" );
$.ajax(
{
type:"GET",
url: "/load",
data:{
},
})
}
});
</script>
...
基本上它在开始时加载 5 个项目,而我试图实现的是,一旦我点击页面底部,它就会再加载 1 个项目。
所以 jQuery 工作,因为 console.log('Test') 工作,在我的终端它说
这也很好。
我想我以某种方式搞砸了 ajax。我不确定。
正如您可能会说我是个菜鸟,但我们非常感谢任何帮助。
最佳答案
使用这样的东西:
import json
from django.http import JsonResponse
def index(request):
if request.method == 'GET':
context = {
'entry_list': Entry.objects.filter()[:5],
}
return JsonResponse(json.dumps(context), safe=False)
else:
return JsonResponse({"err_msg": "Failed"})
关于python - 如何通过 Django 中的 AJAX 请求传递数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50631477/