2014-02-09 116 views
1

我使用Mapquest服务检查是否Ajax请求是空

我要检查,如果该请求是sucessfull的免费地理编码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

在此先感谢

回答

2

周围的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 == 0response == ""将评估为false,因为总会有返回的响应。

+1

非常感谢细节,顺便说一句,URL上额外的单引号是将其标记为代码。不管怎样,谢谢 – slevin

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/

+0

谢谢,但我已经有了这种结构的代码。我有'.done'和'.fail'。我认为一个请求是成功的,并返回空数据,所以与'.done'部分有关。 – slevin

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/

相关问题