简体   繁体   English

如何在Javascript中迭代文件

[英]How can I iterate through files in Javascript

Is it possible to iterate through a collection of files in Javascript? 是否可以在Javascript中迭代一组文件? I am writing a jQuery plugin that takes either an array of images or, I was hoping, a directory containing a list of images. 我正在编写一个jQuery插件,它接受一个图像数组,或者,我希望,一个包含图像列表的目录。 Eg either: 例如:

['image1.jpg','image2.jpg','image3.jpg']

or 'http://somedomain.com/images/' 'http://somedomain.com/images/'

I would then like to be able to iterate through the above domain and take the file name from each of the files in the folder. 然后,我希望能够遍历上面的域并从文件夹中的每个文件中获取文件名。

I have read about the FileSystemObject but this will only be available in IE, is there an equivalent that can be used in all browsers? 我已经阅读过关于FileSystemObject但是这只能在IE中使用,是否有可以在所有浏览器中使用的等价物?

You should use server side language to provide array of images in JSON or similar. 您应该使用服务器端语言来提供JSON或类似的图像数组。 There is no way Javascript can access local files. Javascript无法访问本地文件。 That would be serious security issue. 那将是严重的安全问题。

You can't. 你不能。

You have to get the list from your server through JSON or XML. 您必须通过JSON或XML从服务器获取列表。 Because of this, you can't do this in any way with javascript on servers you have no control over. 因此,您无法以任何方式使用javascript在您无法控制的服务器上执行此操作。 Also, access to client side files is actively avoided for security reasons. 此外,出于安全原因,主动避免访问客户端文件。

You would need to create a web service to fetch the list of files. 您需要创建一个Web服务来获取文件列表。 You can't use ajax to directly fetch the directory listing because ajax calls are restricted to the domain. 您不能使用ajax直接获取目录列表,因为ajax调用仅限于域。

If the directory is on the same domain, and your webserver is setup to show directory indexes, then you could use javascript to request the url and load it into the dom for data extraction. 如果目录位于同一个域中,并且您的Web服务器设置为显示目录索引,则可以使用javascript请求URL并将其加载到dom中以进行数据提取。 This is brittle, and doesn't sound like it would make for a good plugin, much less good for anything but a one off task. 这很脆弱,听起来不像是一个好的插件,除了一次性任务之外的任何东西都不那么好。 But, you could do it. 但是,你可以做到。

The other suggestions of having serverside script output json or xml would be an improvement. 使用服务器端脚本输出json或xml的其他建议将是一种改进。

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

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