为什么只有第一个元素出现在html字符串中才能通过XMLHttp请求?

时间:2017-12-10 18:17:46

标签: javascript

我正在尝试通过XMLHttp请求动态地将mp3文件加载到网页。它是一个字符串,应该有两个带有音频文件的div。但是,只有第一个出现。有人可以帮我确定一下为什么会这样吗?我希望能够将更多文件加载到源页面并让它们动态显示在此网页上。

这是我的代码:

<!DOCTYPE html>
<HTML lang="en-US">
<HEAD>
<TITLE>load files</TITLE>  

<Style>
   body{
       background-color: blue;
   }

   .container{
       border:5px solid white;
       margin:10%;
       width:600px;
       height:600px;

   }

   .floating {
     display: inline-block;
     width: 150px;
     height: 75px;
     margin: 10px;
     border: 3px solid #73AD21;  
  }

</Style>
<SCRIPT>
  function get_list_of_files_from_html( html_string ){
    var el = document.createElement( 'html' );
    el.innerHTML = html_string;

    var list_of_files = el.getElementsByTagName( 'a' ); 

    var return_string = '<div class="floating">';

    for(var i=5; i < list_of_files.length ; i++){
      var current_string = list_of_files[i];
      var new_string  = current_string.toString()
        .replace('http://www.website.com/~user/final/','');
      return_string += 
        '<audio controls><source src ="' + new_string + 
        '" type=audio/mpeg></audio>';
      return_string += '</div>';

      return return_string;
    }
  }

  function loadDoc(){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("container").innerHTML =
        get_list_of_files_from_html( this.responseText);
      }
    };
    xhttp.open("GET", 
      "http://www.website.com/~user/final/audiofiles/", true);
      xhttp.send();
  }

</SCRIPT>
</HEAD>
<BODY>
  <body onload="loadDoc()">
  <div id="container"  class="container"></div>
</body>
</BODY>
</HTML>

2 个答案:

答案 0 :(得分:0)

更新:您已表示需要对字符串进行全局替换。为此,您需要使用正则表达式:

/http:\/\/www.website.com\/~user\/final\//gi

字符串中的正斜杠需要转义。对于全局和不区分大小写,您可能还需要gi

无论如何,您的代码应该重新组织以遵循现代标准。虽然HTML不区分大小写,但它通常用小写(<style>,而不是<Style>等)编写,JavaScript标识符应该在camelCase中,而不是在每个单词之间强调with_long_names_for_stuff。你还有几个不必要的代码。请参阅下面的评论:

&#13;
&#13;
<!DOCTYPE html>
<html lang="en-us">
<head>
  <title>load files</title>  
  <style>
    body { background-color: blue; }

    .container {
      border:5px solid white;
      margin:10%;
      width:600px;
      height:600px;
    }

    .floating {
      display: inline-block;
      width: 150px;
      height: 75px;
      margin: 10px;
      border: 3px solid #73AD21;  
    }
  </style>
</head>
<body>
  <div id="container" class="container"></div>
  
  <!-- Place your scripts just before the close of the body tag and they will
       run as soon as the DOM is built, eliminating the need for: body.onload = ...-->
  <script>
    
    var xhttp = new XMLHttpRequest();
    xhttp.addEventListener("readystatechange", function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("container").innerHTML = getFileList(this.responseText);
      }
    };
    xhttp.open("GET", "http://www.website.com/~user/final/audiofiles/", true);
    xhttp.send();
   
    // Follow standard naming conventions. Don't make crazy long function or variable names
    function getFileList(html){
    
      // Don't create a new HTML element to hold the passed string.
      // Use something that body content normally would go in:
      var el = document.createElement(div');
      el.innerHTML = html;

      // Don't use .getElementsByTagName() as this returns a "live" node list.
      // Instead, use the more efficient, modern approach and place the results
      // in a JavaScript array so that you can loop with .forEach() later:
      var fileList = Array.prototype.slice.call(el.querySelectorAll('a')); 

      var retVal = '<div class="floating">';
      
      // Loop through the array with Array.forEach() which is simpler than
      // setting up counters and managing them:
      fileList.forEach(function(file, idx){
        // Do you really want to ignore the first 6 items?
        if(idx >= 5){
          // No need to call .toString() on string data
          // Use a regular expression to do a global replace on the string
          retVal += '<audio controls><source src ="' +                                  
                    file.replace(/http:\/\/www.website.com\/~user\/final\//gi,'') + 
                    '" type=audio/mpeg></audio></div>';
        }
      });
      
      return retVal;
    } 
  </script>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我需要使用全局变量,因此/http://www.website.com/~user/final//g代替http://www.website.com/~user/final/