Ajax-检查网址是否存在的函数 [英] Ajax - Function to check if Url exists

查看:63
本文介绍了Ajax-检查网址是否存在的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Reddit API构建网站,以显示Reddit的图像.我通过JSON获取数据,然后使用URL作为图像源提供的数据来构建页面.

I'm building a building a website using the Reddit API to display images from Reddit. I'm getting the data via JSON then use it to build the page, using URLs provided as sources for the images.

我获得的某些URL不会直接进入图像,而是进入图像托管站点(例如imgur.com).通常,在网址末尾添加".jpg"会将我带到正确的图片.

Some of the URLs that I get don't go to images directly, but instead to image hosting sites (like imgur.com). Usually, adding '.jpg' at the end of the URL takes me to the right image.

因此,我想在使用URL +'.jpg'之前检查它是否存在.

So, doing that, I would like to check if the URL + '.jpg' exists before using it.

我试图建立一个检查网址的函数.

I tried to build a function to check the url.

function checkUrl(url){
    var request = new XMLHttpRequest;
    request.open('GET', url, true);
    request.send();
    request.onreadystatechange = function(){
        if(request.readyState==4){
            console.log(request.readyState);
            return true;
        }else{
            return false;
        }
    }
};

//Then I use the function to check and append the data to the page
var url = url+'.jpg';
if(checkUrl(url)){
    //work with the data
}else{
    //do nothing
}

页面没有任何反应,仍然可以将readyState登录到控制台,因此checkUrl()函数似乎返回true.

Nothing happens to the page, still I get the readyState logged into the console, so the checkUrl() function seems to be returning true.

我做错了什么?对于整个Ajax事情,我还是很陌生的,因此对您的帮助非常感谢.

What I am doing wrong ? I am pretty new to the whole Ajax thing, so some help would very appreciated.

谢谢

推荐答案

我相信您的问题是对AJAX的误解;AJAX基本上是异步的,所以这就是您要描述的行为的原因.我使用以下内容以同步的方式获得了一个简单的true/false指示URL是否有效:

I believe your problem is misunderstanding of AJAX; AJAX is basically asynchronous, and that's why the behavior you are describing.
I've used the following to get a simple true/false indication whether a URL is valid, in a synchronous manner:

function isValidURL(url) {
    var encodedURL = encodeURIComponent(url);
    var isValid = false;

    $.ajax({
      url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
      type: "get",
      async: false,
      dataType: "json",
      success: function(data) {
        isValid = data.query.results != null;
      },
      error: function(){
        isValid = false;
      }
    });

    return isValid;
}

那么用法很简单:

var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");

希望这会有所帮助

这篇关于Ajax-检查网址是否存在的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆