简体   繁体   English

$ .getJSON(…php,function)其他

[英]$.getJSON(…php, function) else

I'm working with JSON to make my login script, and so I'm using the following in my script: 我正在使用JSON制作登录脚本,因此我在脚本中使用了以下内容:

$.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? 因此,当PHP以JSON返回数据时,将执行代码,但是构建else结构的最佳方法是什么? So when there is no return from PHP/JSON, to execute an other code? 那么,当PHP / JSON没有回报时,要执行其他代码吗?

Thanks in advance 提前致谢

Use jQuery's promises. 使用jQuery的承诺。 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. 您应该检查PHP输出以始终输出一些数据。

Such as this in PHP: 像这样的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: 如果我什么都不输出,我就将false设置为成功,这使得通过data.success在jQuery中进行验证变得容易:

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. 如果您不想修改您的输出,可以设置ajaxError来捕获您的阅读问题。

Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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