我有一个页面,基本上是一个有待售物品的店面。我在导航栏中有一些过滤器来过滤产品。当我点击过滤器时,我试图通过AJAX加载与该过滤器相关的产品(不刷新页面)。目前,当我点击过滤器时,商店商品会消失,但不会重新填充相关商品。我在chrome dev控制台中收到以下错误:
Uncaught TypeError: Cannot read property 'ownerDocument' of undefined jquery.2.1.1.min.css
我不确定发生了什么,我一直在关注这个教程http://westiseast.co.uk/blog/django-ajax-update-queryset-introduction/,这已经过时了,所以我不知道我的问题是否可能与使用依赖于已弃用的库的教程或实践(我正在使用Django 1.6)。
非常感谢任何帮助。
VIEWS.PY
def storefront(request):
latest_entries = Entry.objects.order_by('-pub_date')[:16]
context = {'latest_entries': latest_entries}
if request.is_ajax():
if request.GET.get('filter') == 'recent':
new_list = []
latest_entries = Entry.objects.filter(entrytype=3)
new_list.append(render_to_string('storefrontload.html', {'latest_entries': latest_entries}))
json = simplejson.dumps(new_list, cls=DjangoJSONEncoder)
return HttpResponse(json, content_type='application/json')
return render(request, 'storefront.html', context)
URLS.PY
urlpatterns = patterns('',
url(r"^$", home),
url(r"^storefront/", storefront))
STOREFRONT.HTML
<a href="" id=most_recent>Show Recent</a>
{% include "storefrontload.html" %}
<script>
function filter(type) {
$.getJSON("/storefront/", {xhr: "true", filter: type},
function(data) {
$('.container').children().remove();
$(data).appendTo('.container');
});
}
$("#most_recent").click(function () {
filter("recent");
$('#most_recent').attr('style', 'font-weight: bold').css('color', '#000');
});
return false;
</script>
STOREFRONTLOAD.HTML
<div class="bodydiv">
<div class="container">
{% for i in latest_entries %}
<div class="grid_4">
<div class="imgcontainer">
<img src="{{ i.item_picture.url }}" alt="" />
<div class="overlayname">{{ i.headline }}</div>
<div class="overlayprice">{{ i.price1 }}</div>
</div>
<div class="textcontainer">
<p>{{ i.body_text }}</p>
</div>
<div class="sellerdiv">
<div class="sellerpic"><a href="/accounts/{{ i.author }}"><img src="{{ i.author.get_profile.get_mugshot_url }}"></a></div>
<div class="sellerinfo">Sold by <b>{{ i.author }}</b></div>
<div class="hearts"><img src="/static/img/stars.png"></div>
<div class="reviewnum"></div>
<div class="posteddate">Posted {{ i.pub_date|timesince|upto:',' }} ago</div>
</div>
</div>
{% endfor %}
答案 0 :(得分:0)
你实际上不需要json,只需返回部分html
if request.is_ajax():
if request.GET.get('filter') == 'recent':
latest_entries = Entry.objects.filter(entrytype=3)
context = {'latest_entries': latest_entries}
return render(request, 'storefrontload.html', context)
return render(request, 'storefront.html', context)
并在html中:
function filter(type) {
$.get("/storefront/?filter="+type, function(data) {
$('.container').children().remove();
$(data).appendTo('.container');
});
}