从jQuery调用函数与Django无法正常工作

时间:2011-04-27 21:33:23

标签: javascript ajax django jquery

我试图根据用户标准创建一个搜索用户的页面。然后它通过AJAX响应将结果加载到不同的DIV中:

function search_friends() {
    $("#search-results").show();
    $("#loading1").show();
    var q = $("#id_q").val();
    var type = $("#id_search_type").val();
    $("#loading1").hide();
    $("#results").load("/search/friends/?ajax&q="+encodeURIComponent(q)+"&search_ty­pe="+encodeURIComponent(type));
    return false;
}

在这个新结果DIV中,我为每个用户提供了链接,以便能够将它们添加为朋友。此结果中的每个链接DIV都具有每个用户userID的ID和一个user_link类。当登录用户点击链接时,我希望它弹出一个确认框,然后通过AJAX发送请求。但是,我无法像我想的那样通过AJAX获取链接。我的代码如下:

{% for u in users %}
<div id="results">
    <img src="{{ u.profile_pic }}" class="xsmall-pic" /> <a href="/{{ u.username }}/">{{ u.username }}</a><br />
    <span class="small-date">{{ u.get_full_name }}</span>
    <span class="floatR" id="user_{{ u.id }}_link"><a href="#" id="{{ u.id }}" class="user_link">Add as friend</a></span>
</div>{% endfor %}

<script type="text/javascript" language="javscript">
    $(document).ready(function() {
        var csrf_token = "{{ csrf_token }}";
        $(".user_link").bind('click',function() {
            request_friend($(this).id,csrf_token)
        });
        $("#search-friends-form").submit(search_friends);

    });
</script>

在外部JavaScript文件中,我有以下内容:

function confirm_request()

    return confirm("Are you sure you want to request this user as a friend?");
}

function request_friend(id,token)
    if (confirm_request())
    {
        var data1 = {to_friend: id,csrfmiddlewaretoken: token};
        $.post('/users/requests/friends/'+id+'/?ajax', 
                data1, function(json) {
                    $("#user_"+id+"_link").html(json.status);
                }, "json");
                return false;
    }
    else
    {
        return;
    }
}

感谢您提供任何帮助,因为我对Javascript并不是那么棒。

编辑 通过AJAX调用的Python函数

def search_for_friends(request):
users = False
friends = False
return_page = 'users/friend_search.html'
ajax = 'ajax' in request.GET
try:
    if 'q' in request.GET:
        form = FriendSearchForm(request.GET)
        if form.is_valid():
            if form.cleaned_data['search_type'] == 'username':
                users = CustomUser.objects.exclude(pk=request.user.id).filter(username__icontains=form.cleaned_data['q'])
            elif form.cleaned_data['search_type'] == 'name':
                users = CustomUser.objects.filter(Q(first_name__icontains=form.cleaned_data['q']) | Q(last_name__icontains=form.cleaned_data['q']))
            elif form.cleaned_data['search_type'] == "email":
                users = CustomUser.objects.filter(email__icontains=form.cleaned_data['q'])
            else:
                pass
        else:
            pass
    else:
        form = FriendSearchForm()
    if users != False:
        users = users
        error = False
    if users == "":
        users = ""
        error = "No users match the search term provided"
    if ajax:
        show_results = True
        context = RequestContext(request,{'users':users,'form':form,'show_results':show_results})
        return render_to_response('users/friend_search_results.html',context_instance=context)
    context = RequestContext(request,{'users':users,'form':form,'error':error})
    return render_to_response(return_page,context_instance=context)
except:
    form = FriendSearchForm()
    context = RequestContext(request,{'form':form})
    return render_to_response(return_page,context_instance=context)

3 个答案:

答案 0 :(得分:1)

如果您想避免在AJAX响应中使用JavaScript,则可以让.load()的完成事件负责设置点击事件:

var url = "/search/friends/?ajax&q="+encodeURIComponent(q)+"&search_ty­pe="+encodeURIComponent(type);
$("#results").load(url, function() {
    var csrf_token = "{{ csrf_token }}";
    $(".user_link").bind('click',function() {
        request_friend($(this).id,csrf_token)
    });
});

答案 1 :(得分:1)

如果我理解你的问题,你想确保点击处理程序适用于通过以后的AJAX调用加载的链接吗?

在jQuery中,使用$('.user_link').live('click', function() {})处理程序一次将click事件处理程序分配给所有当前和未来的链接。

答案 2 :(得分:0)

除非您明确告诉jQuery对其进行评估,否则不会评估从您的AJAX调用返回的Javascript。这是通过在AJAX调用上指定dataType来完成的,.load() doesn't support

this answer所示,您应该使用jQuery.get()$.ajax并指定您的数据类型:

$.ajax({
  type: "GET",
  url: "yourPage.htm",
  dataType: "html"
});