簡體   English   中英

檢查ajax請求是否為空

[英]check if ajax request is empty

我使用了mapquest的免費地理編碼API

我想檢查請求是否成功,但未返回任何數據。

我在表單字段中輸入“ vdfsbvdf54vdfd”(只是一個愚蠢的字符串)作為地址。 我希望收到這樣的警報,“抱歉,輸入錯誤”。 警報永遠不會發生。

這是我的代碼片段

$.ajax({
     type: "POST",
     url: "`http://open.mapquestapi.com/geocoding/v1/address?key=012`",
     data: { location: ad, maxResults: 1}
     })


 .done(function( response ) {alert(response);
         var geoclng = response.results[0].locations[0].latLng.lng;
        var geoclat = response.results[0].locations[0].latLng.lat;

        if (geoclng=="") {alert("Sorry, wrong input");}

         //now use lon/lat on map etc
                          )}

我試過了if (geoclng=="") {alert("Sorry, wrong input");}

還要if (response.length=0) {alert("Sorry, wrong input");}

以及if ($.isEmptyObject(response)) {alert("Sorry, wrong input");}

和警報永遠不會發生。

如果有幫助,當我提醒響應時,我得到object Object

提前致謝

刪除網址周圍多余的單引號,並檢查locations數組的長度:

$.ajax({
     type: "POST",
     url: "http://open.mapquestapi.com/geocoding/v1/address?key=012",
    data: { location: ad, maxResults: 1}
     })
 .done(function( response ) {
     alert(response.results[0].locations.length); //if greater than zero, you have results
     if( response.results[0].locations.length > 0 ){
         var geoclng = response.results[0].locations[0].latLng.lng;
         var geoclat = response.results[0].locations[0].latLng.lat;
         //now use lon/lat on map etc
     } else {
         alert("Sorry, wrong input");
     }
  )}

當您運行對http://open.mapquestapi.com/geocoding/v1/address?key=012的調用時,無論是否存在匹配項,它都會返回一個對象。 如果未找到該對象,則該位置數組的內容將為空。

response.length == 0response == ""計算結果為false因為總是返回一個響應。

嘗試以下代碼檢查成功/失敗的請求。

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get("example.php", function() {
    alert("success");
})
.done(function() {
    alert("second success");
})
.fail(function() {
    alert("error");
})
.always(function() {
    alert("finished");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
    alert("second finished");
});

有關更多詳細信息,請參見此鏈接https://api.jquery.com/jQuery.get/

嘗試在您的ajax代碼中添加此代碼:

$.ajax({
  type: "POST",
  url: "http://open.mapquestapi.com/geocoding/v1/address?key=012",
  data: { 
     location: ad, maxResults: 1
  }
})

將其添加(僅在data參數下)

success: function (response) {
  if (response == '') {
    alert('Sorry!');
  }
}

這將在成功事件上運行,並將檢查從服務器返回的響應。 然后使用if else塊測試其值。

我想轉發給您更多有關jQuery Ajax API的信息: http : //api.jquery.com/jquery.ajax/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM