【问题标题】:How to put error message into if statement if(...)如何将错误消息放入 if 语句 if(...)
【发布时间】:2017-05-17 04:18:37
【问题描述】:

我正在尝试从面部识别 API 获取 ajax 响应。响应是人脸的数据特征, 错误信息是

{"Errors":[{"Message":"在图像中找不到人脸","ErrCode":5002}]}

响应消息是

{"images":[{"status":"Complete","width":236,}]}]}

我应该如何编写 If/else 语句,以便在有面/响应时提示“成功”,如果没有面/错误则提示“失败”?

$("#testDetect").click(function () {
    var file = $('#imageFile')[0].files[0]; 
    var reader  = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = function () {
      var imageData = parseImageData(reader.result);
      var data = {};
      data.image = imageData;
      $.ajax({
      url      : "http://localhost/Karios/simple-detect/form-post.php",
      type     : "POST",
      data     :  data,
      dataType : 'text'
   }).done(function(response) {

     console.log(response);

            if (!response) { 

                alert('Hmm, unexpected response from Kairos');
            } else if (response['Errors'] && response['Errors'].size() > 0) { 
                if (response['Errors'][0]['ErrCode'] == 5002) { 

                    alert(response['Errors'][0]['Message']);

                } else {

                    alert('Some other error occurred:\n' + response['Errors']['ErrorCode'] + ': ' + response['Errors']['Message']);

                }
                
            } else { 

                alert('Face(s) detected');
      }  
    })
    }
});

如果有人脸,如果没有人脸则提示“失败”

【问题讨论】:

  • 以及没有错误时得到的响应
  • 你传递给ajax调用的对象,你可以再传递两个字段errorsuccess,这两个都是回调。当有任何错误时,将调用错误回调,否则将调用成功回调。这样你就知道在哪里处理错误了。
  • @UjjwalKumarGupta 如果他们给我回复,我想提醒“成功”。如果他们向我发送错误,我想提醒“失败”。
  • @nurulnabi 感谢您的回复!由于我是编程新手,所以我不知道你在说什么......你能帮我写出代码吗?谢谢!
  • @JimmyLiao,看看我的回答。

标签: javascript jquery html ajax if-statement


【解决方案1】:

实际上 jquery 为每个都提供了一个 .done 和 .fail ,所以:

    $.ajax({
              url      : "http://localhost/Karios/simple-detect/form-post.php",
              type     : "POST",
              data     :  data,
              dataType : 'text'
           }).done(function(response) {
    try {
let jsonResponse = JSON.parse(response);
      if(jsonResponse.Errors && jsonResponse.Errors[0] && jsonResponse.Errors[0].ErrCode ===5002) {alert(jsonResponse.Errors[0].Message);}
    } catch(err) { console.log("bad response");}
                alert( "success" );
           })
          .fail(function() {
            alert( "error" );
          })
          .always(function() {
            alert( "complete" );
          });

【讨论】:

  • 啊,但是如果失败并不意味着 ajax 失败,而是响应中返回的失败指示呢?
  • 已编辑代码以检查错误代码,然后相应地打印消息。
  • 这个新代码假定响应是一个对象 - 作为数据类型 == text - 响应将是文本:p(我在背后很痛苦)
  • 你会恨我的......如果非失败响应不是 JSON 怎么办:p(我可以整天这样,我的妻子一直对我这样做) -该死的,没看到 try catch - 你在我前面 :p 或者,是吗?
  • 那很简单。但是 4xx 状态对于实际响应来说太苛刻了。相反,我希望 api 以 JSON 格式返回数据。错误为 null 或值,视情况而定。
【解决方案2】:
$("#testDetect").click(function () {
    var file = $('#imageFile')[0].files[0]; 
    var reader  = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = function () {
      var imageData = parseImageData(reader.result);
      var data = {};
      data.image = imageData;
      $.ajax({
      url      : "http://localhost/Karios/simple-detect/form-post.php",
      type     : "POST",
      data     :  data,
      dataType : 'text',
      success:function(response){
        alert('success');       //do your stuff here on success
      },
      error:function(xhr, textStatus, errorThrown){
        alert('fail');          //do your stuff here on fail
      }
   })
  }
})

查看errorsuccess 回调。当 ajax 请求成功解析时,将调用 success 回调,指示请求成功,结果将包含在 response 中,否则将调用 error 回调。

【讨论】:

  • 没用...我上传了我在控制台中看到的图片,我认为这可能会有所帮助
  • 删除dataType 字段。这是官方文档中正确的语法,如果发生任何错误,那么您需要弄清楚发生在哪里。
【解决方案3】:

我会假设Errors 键仅在没有匹配项时出现。

{"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]}

一种方法是:

if(response.Errors){
    alert("fail!"); // or you can return the error message
}else{
    alert("success");
}

如果响应总是包含Errors 键,那么:

if(response.Errors.length > 0){ 
    // fail 
} else { 
     //success 
}

【讨论】:

  • 我上传了我在控制台中看到的图片,我认为这可能会有所帮助
【解决方案4】:
      $.ajax({
      url      : "http://localhost/Karios/simple-detect/form-post.php",
      type     : "POST",
      data     :  data,
      dataType : 'text'
   }).done(function(response) {

      if(response.Errors)
      {
      alert("fail!");
      console.log(response.Errors.Message)
    }
    else{
    alert('success!');
    }
      console.log(response)
})

【讨论】:

  • 那么您可能仍然在 json 响应中遇到错误。如果能同时提供错误响应和成功响应就更好了。
  • 查看我发布的图片
  • 请试试这个 - if(!response.images) { alert("fail!"); console.log(response.Errors.Message) } else{ alert('success!'); }
【解决方案5】:

使用AJAX Events 的处理程序而不是响应解析。可以使用Global Ajax Event Handlers注册。
例如,删除.done() 方法并将以下代码附加到您的javascript:

$(document).ajaxSuccess(function() {
  alert("AJAX request is success!");
});
$(document).ajaxError(function() {
  alert("AJAX request completes with an error.");
});

或者处理本地事件:

$.ajax({
   // ...
   success: function(){
     alert("AJAX request is success!");
   },
   error: function(){
     alert("AJAX request completes with an error.");
   }
 });

【讨论】:

  • 你能帮我写出代码吗?我是编程新手 :)
  • Uncaught ReferenceError: TRACKING_NAME is not defined
  • @JimmyLiao,jQuery.ajaxSetup() 中的global 属性是真的吗?请注意,跨域脚本永远不会触发全局事件!
猜你喜欢
  • 2019-12-24
  • 2022-01-13
  • 2015-08-18
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多