[英]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 == 0
或response == ""
计算结果为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.