简体   繁体   English

使用 Ajax 创建博客罐后,我无法进行任何其他 Ajax 调用,并且 JsonResponse 返回空字符串

[英]After creating a blog pot using Ajax I cannot make any other Ajax calls and JsonResponse return empty string

I have built a website where users can post.我已经建立了一个用户可以发布的网站。 After using Ajax to create the post object it seems that I cannot like it.在使用 Ajax 创建帖子 object 之后,我似乎不喜欢它。 Basically my django view returns an empty JsonData.基本上我的 django 视图返回一个空的 JsonData。 So I need to refresh the page for it to work.所以我需要刷新页面才能正常工作。 Below are what I'm using to submit my ajax calls.以下是我用来提交 ajax 调用的内容。

for creating a post:用于创建帖子:

var SaveForm =  function(e){
    e.preventDefault();
    e.stopImmediatePropagation();
    var form = new FormData(this);
    $.ajax({
        url: $(this).attr('data-url'),
        type: $(this).attr('method'),
        data: form,
        cache: false,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(data){
            if(data.form_is_valid){
                $('#post-list div').html(data.posts);
                $('#modal-post').modal('hide');
            } else {
                $('#modal-post .modal-content').html(data.html_form)
            }
            $('.post-like-form').on("click", ".likeBtn", function (e) {
                var like_count = $(".input-like-count", this).val();
                $(".like-count-d").text(like_count);
                e.preventDefault();
                if($(this).find("i").hasClass("fa-thumbs-up")){
                    like_count++;
                    $(".input-like-count", this).val(like_count);
                    $("i", this).removeClass("fa-thumbs-up").addClass("fa-thumbs-down")
                    $(".like-count", this).text(like_count);
                    $(".like-count-d").text(like_count);
                } else {
                    like_count--;
                    $(".input-like-count", this).val(like_count);
                    $("i", this).removeClass("fa-thumbs-down").addClass("fa-thumbs-up")
                    $(".like-count", this).text(like_count);
                    $(".like-count-d").text(like_count);
                }
                var tk = $(this).attr("data-token");
                var pg = $(this).attr('value');
                $.ajax({
                    type: "POST",
                    url: $(this).attr("data-url"),
                    dataType: 'json',
                    data: {'guid_url': pg, 'csrfmiddlewaretoken':tk },
                    success: function (data){
                        var like_count = parseInt($(".like-count", this).text());
                        if($(this).find("i").hasClass("fa-thumbs-up")){
                            like_count++;
                            $(".input-like-count", this).val(like_count);
                            $("i", this).removeClass("fa-thumbs-up").addClass("fa-thumbs-down")
                            $(".like-count", this).text(like_count);
                        } else {
                            like_count--;
                            $(".input-like-count", this).val(like_count);
                            $("i", this).removeClass("fa-thumbs-down").addClass("fa-thumbs-up")
                            $(".like-count", this).text(like_count);
                        }
                        $("#post-detail-container div").html(data.post_detail)
                    },
                    error: function(rs, e){
                        console.log(rs.responeText);
                    },
                });
            });
        }
    })
    return false;
}

Which successuly creates the post object (It takes a lot of time basically my Ajax request takes way to long to be created).它成功创建了 object 帖子(基本上我的 Ajax 请求需要很长时间才能创建)。 After the post is created I cannot like the posts anymore unless I refresh the page!创建帖子后,除非我刷新页面,否则我无法再喜欢这些帖子了!

Here is my like js ajax call (Which I believe it's not causing the issue as it does work if you refersh the page:这是我喜欢的 js ajax 调用(我相信这不会导致问题,因为如果您引用页面它确实有效:

$(document).ready(function (e) {
    $('.post-like-form').on("click", ".likeBtn", function (e) {
        var like_count = $(".input-like-count", this).val();
        $(".like-count-d").text(like_count);
        e.preventDefault();
        if($(this).find("i").hasClass("fa-thumbs-up")){
            like_count++;
            $(".input-like-count", this).val(like_count);
            $("i", this).removeClass("fa-thumbs-up").addClass("fa-thumbs-down")
            $(".like-count", this).text(like_count);
            $(".like-count-d").text(like_count);
        } else {
            like_count--;
            $(".input-like-count", this).val(like_count);
            $("i", this).removeClass("fa-thumbs-down").addClass("fa-thumbs-up")
            $(".like-count", this).text(like_count);
            $(".like-count-d").text(like_count);
        }
        var tk = $(this).attr("data-token");
        var pg = $(this).attr('value');
        $.ajax({
            type: "POST",
            url: $(this).attr("data-url"),
            dataType: 'json',
            data: {'guid_url': pg, 'csrfmiddlewaretoken':tk },
            success: function (data){
                var like_count = parseInt($(".like-count", this).text());
                if($(this).find("i").hasClass("fa-thumbs-up")){
                    like_count++;
                    $(".input-like-count", this).val(like_count);
                    $("i", this).removeClass("fa-thumbs-up").addClass("fa-thumbs-down")
                    $(".like-count", this).text(like_count);
                } else {
                    like_count--;
                    $(".input-like-count", this).val(like_count);
                    $("i", this).removeClass("fa-thumbs-down").addClass("fa-thumbs-up")
                    $(".like-count", this).text(like_count);
                }
                $("#post-detail-container div").html(data.post_detail)
            },
            error: function(rs, e){
                console.log(rs.responeText);
            },
        });
    });
})

These are my views for liking and creating a post:这些是我喜欢和创建帖子的看法:

@login_required
def post_create(request):
    data = dict()
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():  
            post = form.save(False)
            post.author = request.user
            post.save()
            if request.FILES is not None:
                added = []
                images = request.FILES.getlist('images[]')
                for i in images:
                    if i not in added:
                        print(i)
                        image_instance = Images.objects.create(image=i,post=post)
                        image_instance.save()
                        added.append(i)
            data['form_is_valid'] = True
            posts = Post.objects.all()
            posts = Post.objects.order_by('-last_edited')
            data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request)
        else:
            data['form_is_valid'] = False
    else:
        form = PostForm      
    context = {
    'form':form,
    }
    data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request)
    return JsonResponse(data) 

@login_required
def post_like(request,guid_url):
    data = dict()
    post = get_object_or_404(Post, guid_url=guid_url)
    user = request.user
    if post.likes.filter(id=user.id).exists():
        post.likes.remove(user)
    else:
        post.likes.add(user)
    #posts = Post.objects.all()
    #posts = Post.objects.order_by('-last_edited')
    #data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request)
    if request.is_ajax():
        guid_url = post.guid_url
        data['post_detail'] = render_to_string('home/posts/post_detail.html',{'post':post,'guid_url':guid_url},request=request)
        return JsonResponse(data)

what happens is that after posting when I like a post it goes to the post_like url instead of just liking the post.发生的事情是,当我喜欢一个帖子后,它会转到 post_like url 而不是仅仅喜欢该帖子。 I do not know what is causing this issue as I get no errors in either console or terminal.我不知道是什么导致了这个问题,因为我在控制台或终端中都没有错误。

I appreciate all the help in advance!我提前感谢所有帮助!

just notice that it need a semicolon with a line in inner ajax.请注意,它需要一个分号,内部 ajax 中有一行。

data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM