开发者

Always get the error callback on jQuery.ajax (Rails)

开发者 https://www.devze.com 2023-01-06 13:35 出处:网络
I\'am having a strange error, likely it is a server-side issue. My error callback is always triggered, even when the response status is 200!

I'am having a strange error, likely it is a server-side issue. My error callback is always triggered, even when the response status is 200!

Javascript //client

function save_pomodoro(){
j.ajax({
    url: '/app/save_pomodoro',
    dataType: 'json',
    cache : false,
    success: save_pomodoro_suc,
    error:   save_pomodoro_err,
    data: {
        bar: 'foo'
    }
})
}

function save_pomodoro_suc(data){
 alert("Pomodoro Saved Succesfuly")
}

function save_pomodoro_err(data){
 show_error(data.status, data.responseText) // on success => 200, "OK"
                                            // on fail 4开发者_如何学JAVA00, "bla bla bla"
}

Rails //controller

def save_pomodoro

...

p = Pomodoro.new( params[:bar] )

if p.save
  respond_to do |format|
    format.html { redirect_to :action => 'index' }
    format.js {   render( :json => "OK" ) }
  end
else
  respond_to do |format|
    format.html { redirect_to :action => 'index' }
    format.js {   render( :json => p.errors.full_messages.to_json, :status => 400 ) }
  end
end

end

I have another function (ajax+server) on this same controller that have working callbacks.

This is mysterious for me, so any insights will help

Update: Found Error:

format.js {   render( :json => ["OK"] ) }

Apparently the string by itself isn't a valid json.


One useful way to debug this is to change the signature of your error handler from

function save_pomodoro_err(data)

to

function save_pomodoro_err(XMLHttpRequest, textStatus, errorThrown)

and add an alert or some such (or debug using Firebug) to get the errorThrown string.

which will give you access to the specific error message thrown: you can get passed to the error handler for reasons other than a failed HTTP status, such as a parse error on the JSON, or a timeout.


try this:

j.ajax({
    url: '/app/save_pomodoro',
    dataType: 'json',
    cache : false,
    success: function() { save_pomodoro_suc() },
    error: function() { save_pomodoro_err() },
    data: {
        bar: 'foo'
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号