jQuery不为Rails标准REST DELETE答案调用$ .ajax上的成功方法 [英] jquery doesn't call success method on $.ajax for rails standard REST DELETE answer

查看:58
本文介绍了jQuery不为Rails标准REST DELETE答案调用$ .ajax上的成功方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这样的问题并不新鲜,但是我没有发现任何类似的问题.我有这样的jQuery代码:

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

我的Rails控制器看起来像这样:

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

这正在工作.

但是当我使用以下内容(由标准生成)时,不会调用success回调:

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

经过rails 3.0.3jQuery 1.4.2Firefox 3.6.13的测试.
Firebug说,在两种情况下都会触发该查询并返回200 OK,在两种情况下都将删除项目.但是在第二种情况下,回调不会被调用.

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.

REST是否有显着差异,是否有一种通过使用脚手架控制器来利用jQuery的方法?

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

推荐答案

我已经遇到过几次了,答案看似简单.

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

您在$ .ajax调用中使用了dataType : 'json',因此jQuery需要JSON响应.使用head :ok,Rails返回包含单个空格的响应( http://github.com/rails/rails/issues/1742 ),但jQuery不接受它作为有效的JSON.

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.

因此,如果您真的希望收到错误或仅显示200 OK标头,只需在请求中设置dataType : 'html'即可,它应该可以工作(如果您未设置dataType,则jQuery会尝试猜测类型是什么)基于响应标头等,并且仍然可以猜测json,在这种情况下,您仍然会遇到此问题).如果您实际上希望返回JSON,则可以使用@caseem

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

这篇关于jQuery不为Rails标准REST DELETE答案调用$ .ajax上的成功方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆