如果(...)如何将错误消息放入if语句

时间:2017-05-17 04:18:37

标签: javascript jquery html ajax if-statement

enter image description here我试图通过面部识别API获取ajax响应。响应是面部的数据特征, 错误信息是

  

{"错误":[{"消息":"在图像中找不到面孔"," ErrCode":5002}] }

回复信息是

  

{&#34;图像&#34;:[{&#34;状态&#34;:&#34;完整&#34;&#34;宽度&#34;:236,}]}]} < / p>

我应该如何编写If / else语句,以便我能提醒&#34;成功&#34;如果有面子/反应,警告&#34;失败&#34;如果没有面子/错误?

&#13;
&#13;
$("#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');
      }  
    })
    }
});
&#13;
&#13;
&#13;

如果有脸和警告&#34;失败&#34;如果没有脸

5 个答案:

答案 0 :(得分:2)

实际上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" );
          });

答案 1 :(得分: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回调。

答案 2 :(得分:1)

我认为只有在没有匹配时才会出现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 
}

答案 3 :(得分:0)

      $.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)
})

答案 4 :(得分:0)

使用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.");
   }
 });
相关问题