在以下情况下,当错误来自 PHP 作为对 ajax 请求的响应时,如何显示警报


How to show alert when error comes from the PHP as response to ajax request in following case?

jQuery AJAX函数如下:

$(document).ready(function() { 
    $("#zip_code").keyup(function() {
        var el = $(this);
        var module_url = $('#module_url').val();
        if (el.val().length === 5) {
            $.ajax({
                url : module_url,
                cache: false,
                dataType: "json",
                type: "GET",
                async: false,
                data: {
                    'request_type':'ajax', 
                    'op':'get_city_state',
                    'zip_code' : el.val()
                },
                success: function(result, success) {
                    $("#city").val(result.place_name);
                    $("#state_code").val(result.state_code);
                }
            }); 
        }
    });
});

PHP代码如下:

case "get_city_state":
    // to get the city and state on zip code.
    $ret = $objUserLogin->GetCityState($request); 
    if(!$ret) { 
        $error_msg = $objUserLogin->GetAllErrors();
        $data = array();
        $data['error_message'] = $error_msg;
        $data = json_encode($data);
        echo $data;
        die;
    } else {
        $data = array();
        $data = $objUserLogin->GetResponse();
        echo json_encode($data);
        die;
    }    
    break;

现在,我可以在响应没有任何错误时打印成功,但是当发生某些错误时显示警报消息呢?如何实现?需要对上述代码进行哪些更改?请帮助我。

成功使用以下条件:

    success: function(result, success) {
      if($.inArray( "error_message", result)) {
          alert("Error message");
      } else {
          $("#city").val(result.place_name);
          $("#state_code").val(result.state_code);
      }
    }
on php file if u found data acc to ur parameter
than it ok if there is no data acc to ur parameter than this time u can call its an error so in thsi case  echo "error";
and on ajax page check for result if its value is error then do what else u want 
success: function(result, success) {
          $("#city").val(result.place_name);
          $("#state_code").val(result.state_code);
        }