2014-11-05 86 views
-1

jQuery的AJAX功能如下:在以下情況下,如果錯誤來自PHP作爲對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; 

現在我能打印成功,當談到迴應沒有任何錯誤,但怎麼樣當出現錯誤時顯示警報消息。如何實現它?上述代碼需要做什麼修改?請幫幫我。

+0

檢查錯誤消息長度或進行狀態代碼,並檢查該 – Spokey 2014-11-05 12:02:05

+0

只是檢查'result.error_message'或PHP返回錯誤頭火ajax錯誤回調 – 2014-11-05 12:02:09

+0

發送500/403或其他錯誤代碼,'.fail()'將觸發。檢查[**這個**](http://stackoverflow.com/questions/1632159/how-to-send-a-server-error-response-using-php) – itachi 2014-11-05 12:04:41

回答

2

使用以下條件的成功:

success: function(result, success) { 
     if($.inArray("error_message", result)) { 
      alert("Error message"); 
     } else { 

      $("#city").val(result.place_name); 
      $("#state_code").val(result.state_code); 
     } 
    } 
-1
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); 
     } 
相關問題