简体   繁体   中英

$.getJSON(…php, function) else

I'm working with JSON to make my login script, and so I'm using the following in my script:

$.getJSON("link to PHP where to get the JSON data from", function (data) { // THE CODE TO BE EXECUTED });

So when there is an data return from the PHP in JSON, the code will be executed, but what is the best way to make an else structure? So when there is no return from PHP/JSON, to execute an other code?

Thanks in advance

Use jQuery's promises. From the docs :

var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

You should check your PHP output to always output some data.

Such as this in PHP:

$result = array (
 'success' => true,
 'data' => $data
);
echo json_encode($result);

If I don't output anything, I put false into success, which makes it easy to validate in jQuery via data.success:

Example:

$.getJSON('your_url'), {parameters}, function(data){
 if (data.success) {
  alert('Result');
 } else {
  alert('Empty');
 }
});

If you don't want to modify your output, you can setup an ajaxError to catch your reading problems.

Example:

$.ajaxError(function() {
 alert('error triggered');
});

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