gpt4 book ai didi

javascript - Django:Jquery 单击功能在 Ajax 中不起作用

转载 作者:行者123 更新时间:2023-12-03 12:21:06 26 4
gpt4 key购买 nike

我一直在通过 Tango 和 Django 练习来初步了解 Django。快完成了,但遇到了问题 Ajax part

未调用自动添加页面的 Ajax 函数。我不知道问题是什么,因为正在调用其他函数。在 shell 提示符下,根本没有调用 ajax 函数。需要帮助。

附上相关代码。它与上面的网站链接相同。静态/rango-ajax.js

  $('.rango-add').click(function(){
var catid = $(this).attr("data-catid");
var title = $(this).atrr("data-title");
var url = $(this).attr("data-url");
$.get('/rango/auto_add_page/', {category_id: catid, url: url, title: title}, function(data){
$('#pages').html(data);
me.hide();
});
});

templates/rango/category.html

{% if user.is_authenticated %}
<button data-catid="{{category.id}}" data-title="{{ result.title }}" data-url="{{ result.link }}" class="rango-add btn btn-mini btn-info" type="button">Add</button>
{% endif %}

rango/views.py

@login_required
def auto_add_page(request):
context = RequestContext(request)
cat_id = None
url = None
title = None
context_dict = {}
if request.method == 'GET':
cat_id = request.GET['category_id']
url = request.GET['url']
title = request.GET['title']
if cat_id:
category = Category.objects.get(id=int(cat_id))
p = Page.objects.get_or_create(category=category, title=title, url=url)
pages = Page.objects.filter(category=category).order_by('-views')

#Adds our results list to the template context under name pages.
context_dict['pages'] = pages

return render_to_response('rango/page_list.html', context_dict, context)

rango/urls.py

urlpatterns = patterns('', 
url(r'^$', views.index, name='index'),
url(r'^goto/$', views.track_url, name='track_url'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^auto_add_page/$', views.auto_add_page, name='auto_add_page'),

完整代码在此link

最佳答案

你的代码很好,你唯一要做的就是在/tango/templates/rango/page_list.html中定义你的模板。该模板有以下代码:

 {% if pages %}
<ul>
{% for page in pages %}
<li>
<a href="{% url 'goto' %}?page_id={{page.id}}"> {{ page.title}}</a>
{% if page.views > 1 %}
({{page.views}} views)
{% elif page.views == 1 %}
({{page.views}} view)
{% endif %}
</li>
{% endfor %}
</ul>
{% else %}
<strong> No Pages currently in category. </strong>
{% endif %}

在类别模板内,您必须定义以下代码:

% if category %}
{% if user.is_authenticated %}
<a href="/rango/category/{{ category_name_url }}/add_page/"> Add a new Page</a> <br>
{% endif %}
{% if pages %}
<div id="pages">
<ul>
{% for page in pages %}
<li>
<a href="{% url 'goto' %}?page_id={{page.id}}"> {{ page.title}}</a>
{% if page.views > 1 %}
({{page.views}} views)
{% elif page.views == 1 %}
({{page.views}} view)
{% endif %}
</li>
{% endfor %}
</ul>
</div>
{% else %}
<strong> No Pages currently in category. </strong>
{% endif %}
{% else %}
The specified category {{ category_name }} does not exist!
{% endif %}

关于javascript - Django:Jquery 单击功能在 Ajax 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24449565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com