简体   繁体   English

如何使用 jQuery ajax 检查文件是否存在于 JS 数组中?

[英]How to use jQuery ajax to check if file exists in JS array?

I have an array urlResult which collects the href attribute of all a elements on a component.我有一个数组urlResult ,它收集组件上所有a元素的href属性。 Looks like:好像:

在此处输入图片说明

All I need to do is use jQuery $.ajax() method to check against those URL's and in each callback do something if there is success or failure.我需要做的就是使用 jQuery $.ajax()方法来检查这些 URL,如果成功或失败,在每个回调中做一些事情。 So I was thinking of something like:所以我在想这样的事情:

$.ajax({
    url: urlResult[i] // somehow use dynamic variable?
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

I just need some guidance on how to dynamically include urlResult variable and pass each index to url property in ajax call.我只需要一些关于如何动态包含urlResult变量并将每个索引传递给 ajax 调用中的url属性的指导。

You can use .forEach() to loop over the array of hrefs, and then execute your code inside the loop您可以使用.forEach()循环遍历 href 数组,然后在循环内执行您的代码

 const urlResult = ['www.google.com', 'www.test.com', 'www.demo.com', 'www.aaaa.net']; urlResult.forEach((href) => { $.ajax({ url: href, type: 'HEAD', error: function() { console.log('HREF was ' + href); console.log('error'); }, success: function() { console.log('HREF was ' + href); console.log('success'); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Consider the following code.考虑以下代码。

$(function() {
  function checkFile(u) {
    var result = false;
    $.ajax({
      url: u
      type: "HEAD",
      success: function() {
        result = true;
      }
    });
    return result;
  }

  $.each(urlResult, function(i, v) {
    if (checkFile(v)) {
      // File exists, do the needful
    }
  });
});

Remember that success is only called when HTTP Status is 200 .请记住,只有当 HTTP 状态为200时才会调用success I used $.each() to iterate over the Array.我使用$.each()遍历数组。

The $.each() function is not the same as $(selector).each() , which is used to iterate, exclusively, over a jQuery object. $.each()函数与$(selector).each() ,后者用于专门遍历 jQuery 对象。 The $.each() function can be used to iterate over any collection, whether it is an object or an array. $.each()函数可用于迭代任何集合,无论是对象还是数组。 In the case of an array, the callback is passed an array index and a corresponding array value each time.在数组的情况下,回调每次都会传递一个数组索引和相应的数组值。

See More:查看更多:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM