javascript Ajax - 检查 Url 是否存在的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14764115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:31:07  来源:igfitidea点击:

Ajax - Function to check if Url exists

javascriptajaxreadystate

提问by Simon Be

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.

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

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 不直接转到图像,而是转到图像托管站点(如 imgur.com)。通常,在 URL 末尾添加“.jpg”会将我带到正确的图像。

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

所以,这样做,我想在使用它之前检查 URL + '.jpg' 是否存在。

I tried to build a function to check the url.

我试图构建一个函数来检查 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
}

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

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

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

我做错了什么?我对整个 Ajax 事情还很陌生,所以非常感谢一些帮助。

Thank you

谢谢

回答by joeltine

Your problem is that when request.readyState == 4this means the request has completed, regardlessof what the result of that request was. So even if the URL you request returns a "404 not found", you'll still see the XHR resolving itself to readyState 4.

您的问题是,当request.readyState == 4这意味着请求已完成时,无论该请求的结果如何。因此,即使您请求的 URL 返回“404 not found”,您仍然会看到 XHR 将自身解析为 readyState 4。

To address what you're trying to do, I'd recommend checking the status code of the response. For example, using your code:

为了解决您要执行的操作,我建议您检查响应的状态代码。例如,使用您的代码:

if(request.status==200){
   return true;
}

回答by Samuel Liew

Why your code won't work:

为什么您的代码不起作用:

Your AJAX request is asynchronous, and if(checkUrl(url)){will return null (false) as the function checkUrl()sends the AJAX request and immediately returns, before the AJAX call has completed.

您的 AJAX 请求是异步的,并且if(checkUrl(url)){会在函数checkUrl()发送 AJAX 请求并在 AJAX 调用完成之前立即返回时返回 null (false) 。

Change

改变

request.open('GET', url, true);

to

request.open('GET', url, false);

Also, move your request.send()to after the request.onreadystatechange()as now it is a non-async request.

另外,将您request.send()移到之后,request.onreadystatechange()因为现在它是一个非异步请求。

request.onreadystatechange = function(){
    if(request.readyState==4){
        console.log(request.readyState);
        return true;
    }else{
        return false;
    }
}
request.send();

Or, you could simply place your check logic into the onreadystatechange function:

或者,您可以简单地将检查逻辑放入 onreadystatechange 函数中:

request.onreadystatechange = function(){

    var url = url+'.jpg';
    if(request.readyState==4){
        //work with the data
    }else{
        //do nothing
    }
}

回答by Ohad

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:

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

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;
}

The usage is then trivial:

用法很简单:

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

Hope this helps

希望这可以帮助

回答by Lim H.

The returnvalue of request.reonreadystatechangeis not the returnvalue of checkUrl. Try this:

returnrequest.reonreadystatechange不是returncheckUrl的值。试试这个:

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);
            // perform your data manipulation here
            // don't separate it with the request
        }
    }
};

回答by Venkateswarlu.NP

On Safari, ActiveXObjectwill work fine, compared to XMLHttpRequest:

与 SafariActiveXObject相比,在 Safari 上可以正常工作XMLHttpRequest

function isThere(url)
{
    var req= new AJ(); // XMLHttpRequest object
    try {
        req.open("HEAD", url, false);
        req.send(null);
        //alert(req.status); //un-comment if need alert for status code

        return req.status== 200 ? true : false;
    }
    catch (er) {
        //alert ('ERROR:'); // un-comment if need alert for error
        return false;
    }
}

function AJAX()
{
    var obj;
    if (window.XMLHttpRequest) obj= new XMLHttpRequest();
    else if (window.ActiveXObject)
    {
        try
        {
            obj= new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        catch(er)
        {
            try
            {
                obj= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(er)
            {
                obj= false;
            }
        }
    }
    return obj;
}