简体   繁体   English

如何在此jQuery脚本中编写条件语句?

[英]How to write a conditional statement amidst this jQuery script?

I have a jquery function which targets a rails form and upon the submit event posts the form data to the appropriate action. 我有一个针对Rails表单的jquery函数,并且在Submit事件中将表单数据发布到适当的操作。 The object that's created, a review, is then returned and via a mustache template is appended to a selected element and rendered: 然后返回创建的对象(审阅),并通过胡须模板将其附加到所选元素并进行渲染:

$(document).ready(function(){
     $('.new_review').on('submit', function(event){
        event.preventDefault();
        var reviewList = $(this).siblings('ul’);
        $.post($(this).attr('action'), $(this).serialize(), function(review){
            var newReview = Mustache.render($('#review_template').html(), review);
            reviewList.append(newReview);
        });
    });
});

I have in my reviews controller written an if else statement in order to restrict a user (a devise model) to only being able to create one review: 我在评论控制器中编写了if else语句,以限制用户(设计模型)只能创建一个评论:

def create
    @restaurant = Restaurant.find(params[:restaurant_id])
    @review = @restaurant.reviews.new(params[:review].permit(:thoughts, :rating))

    if @restaurant.reviews.find_by user_id: current_user.id
        flash[:notice] = "You already reviewed this restaurant!” 
        redirect_to '/restaurants’
    else
        @review.user = current_user
        @review.save
        redirect_to '/restaurants' unless request.xhr?
    end
end

However I now need to insert a conditional into my jquery to ensure that it only attempts to append a new object if a review object is actually returned after the post action. 但是,我现在需要在我的jquery中插入一个条件,以确保它仅在发布操作后实际上返回了检查对象的情况下才尝试追加新对象。 I'm thinking that this needs to be written into the third argument on the post function but am a bit lost as to how to go about it. 我认为这需要写到post函数的第三个参数中,但是对于如何处理它有点迷失了。

Could anyone whether this is indeed the right way to go about what i'm trying to achieve and how exactly I could write this. 任何人都可以问这是否真的是实现我要实现的目标以及如何准确编写此目标的正确方法。 Thanks in advance from a JS newbie. 在此先感谢JS新手。

The below now works perfectly with one simple if statement in the post function: 现在,以下内容可以与post函数中的一个简单if语句完美配合:

$(document).ready(function(){
  $('.new_review').on('submit', function(event){
    event.preventDefault();
    var reviewList = $(this).siblings('ul');
    $.post($(this).attr('action'), $(this).serialize(), function(review){
      var newReview = Mustache.render($('#review_template').html(), review);
      if review 
        reviewList.append(newReview);
    });
  });
});

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

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