jquery - 加载所有文本文件并显示它们

jul*_*ian 3 ajax jquery

我一直在使用jQuery很长时间,但我从来没有学过AJAX,所以我来了..

我们有这个代码:

$('body').load('hello.txt');
Run Code Online (Sandbox Code Playgroud)

很简单,现在让我说我有多个文本文件(我不知道他们的名字)我想加载,
我可以这样做吗?也许我需要循环所有文本文件并以某种方式加载它们?

提前致谢

Beh*_*ili 6

假设您在特定位置的服务器中有文本文件,则可以执行以下操作:

HTML标记:

 <div id="fileList">
       here list of files will be loaded so that user can select which one to load
 <div>

 <div id="file-content">
       content of selected file will be loaded here
 <div>
Run Code Online (Sandbox Code Playgroud)

JQuery部分:

 $.ajax({
      url : "FileServer/GetFileNames", // this is just a url that is responsible to return files list 
      success : function(data){
          //here a JSON data including filenames expected 
          $.each(data,function(i,item){
                var $fileHolder = $("<div></div>");
                $fileHolder.attr("filename",item.filename).click(function(){
                      $("#file-content").load($(this).attr("filename"));
                }).html(item.filename).appendTo("#fileList");  
          });
      }
 });
Run Code Online (Sandbox Code Playgroud)

JSON结构预期

   [
      {
          filename : "text1.txt"
      },
      {
          filename : "text2.txt"
      },
      {
          filename : "text3.txt"
      } 
   ]
Run Code Online (Sandbox Code Playgroud)

在服务器端实现文件列表取决于您.