开发者

calling function from jQuery with Django not working correctly

开发者 https://www.devze.com 2023-03-01 16:54 出处:网络
Im trying to make a page that searched for users based on a users criteria. It then开发者_JAVA技巧 loads the results via AJAX response into a different DIV:

Im trying to make a page that searched for users based on a users criteria. It then开发者_JAVA技巧 loads the results via AJAX response into a different 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;
}

Inside this new results DIV, I have links for each user to be able to add them as a friend. Each link in this results DIV has a ID of each users userID and a class of user_link. When the logged in user clicks on the link I want it to pop up a confirmation box then send the request via AJAX. However, I cannot get the links to submit via AJAX like I want. The code I have is below:

{% 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>

In an external JavaScript file I have the following:

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;
    }
}

Thanks for any help as Im not all that great with Javascript.

EDIT Python function called via AJAX

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)


If you want to keep from having the JavaScript in the AJAX response, you could have the completion event of .load() take the responsibility of setting up the click events:

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)
    });
});


if I understand your question correctly, you want to make sure click handlers work for links loaded through a later AJAX call?

In jQuery, use the $('.user_link').live('click', function() {}) handler once to assign a click event handler to all current and future links.


The Javascript being returned from your AJAX call does not get evaluated unless you specifically tell jQuery to evaluate it. This is done by specifying the dataType on your AJAX calls, which .load() doesn't support.

As seen in this answer, you should use jQuery.get() or $.ajax and specify your data type:

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

精彩评论

暂无评论...
验证码 换一张
取 消