Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

jquery doesn't call success method on $.ajax for rails standard REST DELETE answer

May be such problem is not new, but I didn't find anything similar. I have such jQuery code:

$.ajax({ 
  url : ('/people/'+id), 
  type : 'DELETE', 
  dataType : 'json', 
  success : function(e) {
    table.getItems(currentPage);
  }
});

My Rails controller looks like this:

def destroy
    @person = Person.find(params[:id])
    @person.destroy

    respond_to do |format|
      format.html { redirect_to(people_url) }
      format.json  { render :json => @person, :status => :ok }
    end
end

This is working.

But when I use the following (as generated by standard), the success callback doesn't get called:

def destroy
    @person = Person.find(params[:id])
    @person.destroy

    respond_to do |format|
      format.html { redirect_to(people_url) }
      format.json  { head :ok }
    end
end

Tested under rails 3.0.3, jQuery 1.4.2 and Firefox 3.6.13.
Firebug says, that query is fired and returns 200 OK in both cases, item is deleted in both cases too. But in second case the callback is not called.

Is there a significant difference in REST, and is there a way to utilize jQuery by using the scaffolded controller?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have run across this a few times and the answer is deceptively simple.

You are using dataType : 'json' in your $.ajax call, so jQuery is expecting a JSON response. With head :ok Rails returns a response containing a single space (http://github.com/rails/rails/issues/1742), which is not accepted by jQuery as valid JSON.

So if you really expect to get either an error or a bare 200 OK header, just set dataType : 'html' in your request and it should work (if you don't set dataType, jQuery will try to guess at what the type is based on response headers, etc., and could still guess json, in which case you'd still have this problem). If you actually expect to get JSON back, instead of using head :ok render something valid with JSON (see comments) or just use head :no_content as suggested by @Waseem


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...