2

我使用 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

提前致谢

4

3 回答 3

4

删除 url 周围多余的单引号并检查位置数组的长度:

$.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 == 0orresponse == ""将评估为,false因为总是返回响应。

于 2014-02-09T16:07:23.263 回答
0

尝试下面的代码来检查成功/失败的请求。

// 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/

于 2014-02-09T16:00:38.307 回答
0

尝试在您的 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/

于 2014-02-09T16:00:49.117 回答