如何基于ajax响应警告您想要的任何响应

时间:2017-05-16 16:30:48

标签: javascript php jquery ajax

enter image description here我正在制作面部识别系统。我使用了名为Kairos的API。我得到的响应是面部特征的数据或来自非面部图像的错误消息。如何更改响应并在屏幕上显示它们,例如"成功!这是一张脸"或者"没有面孔"。我尝试了if / else语句,但似乎没有回复。我该怎么办?



<script>
$("#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) { // Something unexpected happened. The message body is empty.

            alert('Hmm, unexpected response from Kairos');

        } else if (response['Errors'] && response['Errors'].size() > 0) { // If Errors is defined in the response, something went wrong.

            if (response['Errors'][0]['ErrCode'] == 5002) { // This appears to be the error when no faces are found.

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

            } else {

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

            }
            
        } else { // If there are no errors in the response, can we assume it detected a face? I guess so.

            alert('Face(s) detected');
            // The response has a ton of information about what it saw, including gender, age, ethnicity
            // and more.

        }
  
})
}
});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

根据您收到的回复,您可以写下您想要显示的内容:

if(response === true){
  alert('success!');
}
else{
  alert('fail!');
}

修改

要重定向到其他页面,请使用:window.location = http://mywebsite.com;

要使按钮不可点击,您需要设置已禁用的属性:document.querySelector('button').setAttribute('disabled',true);

修改

如果这是您的回复:{"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]}那么您必须首先解析它,因为它很可能是一个字符串。然后在条件语句中,检查它是否存在。

var obj = '{"Errors":[{"Message":"no faces found in the image","ErrCode":5002}]}';

obj = JSON.parse(obj);

if(obj.Errors){
console.log("errors exist");
}

答案 1 :(得分:0)

除了.done()之外,您还可以调用{a}会在ajax失败时运行的.fail()

$("#testDetect").click(function() {
  var data = {}
  $.ajax({
    url: "http://localhost/Karios/simple-detect/form-post.php",
    type: "POST",
    data: data,
    dataType: 'text'
  }).done(function(response) {
    alert(response)
  }).fail(function(error) {
    alert("Not a face")
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testDetect">Test</button>