简体   繁体   中英

jQuery ajax success event Strangely not working on ajaxSetup

Background:

  • Using jQuery 1.7 client side
  • PHP server side
  • Using json responses with json_encode php function
  • The content-type header is correct, any of these works: text/plain,text/x-json,application/json.
  • There's no errors thrown from my php code
  • Am working on Firefox 11
  • Am using the js console and the other web's developer tools
  • HTTP/1.1 200 OK

In this Javascript code, the success event is never fired:

$.ajaxSetup({cache:false,
        success:function(d) {
            console.log("ok from setup with data "+d.toSource())
        },
        complete:function(xhr,ts){
            console.log("Ajax finished reponse:"+xhr.responseText)
        },
        error:function(jqXHR, textStatus, errorThrown){
            console.log("Error")
        }
});
$.getJSON("test2.php",{},function(data){
    //some code here
});

When I do it this way, it works:

$.ajaxSetup({cache:false,                
        complete:function(xhr,ts){
            console.log("Ajax completado con:"+xhr.responseText)
        },
        error:function(jqXHR, textStatus, errorThrown){
            console.log("Error")
        }
});
$.getJSON("test2.php",{},
     function(data){
            //some code here
     }).success(function(d){
            console.log("success applied directly, data "+d.toSource())
        }
);

In both cases the complete event is always fired and the error one never. However, in the second code the success is fired. Obviously for .get() method it's the same.

PHP code:

<?php header("Content-Type:application/json;charset=utf-8");
    //or whatever text/x-json text/plain, even text/html, jquery do the dirty job
echo json_encode(array("stat"=>"1")) ?>

My objectives:

  1. I want to fire the same success event to all ajax requests
  2. I want to use the json data returned by the request in my success event, and if it is possible, without convert the raw jqXHR responseText to a json again

The problem is strange, any ideas?


I read all these questions:

And I'm pretty sure none of them are my problem.

Take a look at the ajaxSetup documentation: http://api.jquery.com/jQuery.ajaxSetup/

Note: Global callback functions should be set with their respective global Ajax event handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than within the options object for $.ajaxSetup().

I think that's your problem right there.

UPDATE

If you want your ajax handlers to be global for any ajax request on the page, do something like this:

$(document).ajaxSuccess(function(d){
    console.log("ok from setup with data "+d.toSource());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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