Parser error when using jQuery-UJS for remote link_to in Rails 3 app: how can I debug this?

后端 未结 7 1951
刺人心
刺人心 2021-02-14 12:55

I\'m trying to replace the content of a div after clicking on a link using Rails 3, remote_link :remote => true and jQuery.

So far, I\'ve been able to ge

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 13:39

    If you are attempting to update the contents of a DIV using a normal JQuery AJAX call using the HTML output from a rails controller action, you need to tell JQuery what dataType to expect on the response, so that it will not parse the response as javascript and give you the parsererror you describe.

    $.ajax({ url: "/blah", 
      contentType: "text/javascript", dataType: "html",
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Accept', 'text/javascript');    
      }, 
      success: function(data) {
        $('your-div').html(data);
      }
    });
    

    This would then be compatible with a controller action that uses the respond_to block:

    respond_to do |format|
      format.html {
        # This would be a normal render of your template.
      }
      format.js {
        # This would be a render of your template, as HTML, but only for your AJAX requests.
        # We might use this to avoid including the layout of our template.
        render :layout => nil 
      }
    end
    

提交回复
热议问题