简体   繁体   中英

How to cancel an ajax query (from jquery) on the server side?

Sounds like a weird question, but say I have something like this:

$.post( "/myajax.php",
        { "param1": value1, "param2": value2 },
        function( data, status ) {
            if( status == "success" ) {
               $("#someid").html( data );
            }
        }, "html" );

While myajax.php is doing whatever it needs to do, it decides that it does not need to make any changes to #someid . If it just returns, the someid element is blanked, but I want to leave it alone. How can the php query return in such a way that status != "success" ?

Wouldn't it be simpler to check on the data returned?

$.post( "/myajax.php", { 
        "param1": value1, 
        "param2": value2 
   }, function( data, status ) {
       if( data != "" ) {
           $("#someid").html( data );
       }
   }, 
   "html" 
);

the ajax calls treat any 200 OK as success. as such you could return something else from your PHP script to trigger an error in your ajax.

here are some other status codes in case you wanted to choose something more appropriate.

edit : i don't necessarily disagree with that approach, but i'm still leaning more towards operating on the status message (http status) rather than the response body.

my thoughts are, in a post transaction as the one mentioned, you are updating a resource. one could reasonably assume you expect one of two things two happen (in "success" conditions):

  1. a 200 OK means the content was posted without issue, and the resulting response typically is to show the new content. the ajax method "enforces" this behaviour by allowing you to get the response body to update your UI.

  2. in a scenario where the update does not need to be done, a 200 OK is fine as well (as the request was processed as expected), but perhaps as 204 No Content is better, as it suggests the request is fulfilled, but no change of the view is necessary. i'm leaning towards believing this is more inline with the ajax call as well, as you can ignore the response body (as there is none) and operate on the status (204? update UI to say "no changes were necessary" or similar)

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