当前位置: 代码迷 >> JavaScript >> 将XMLHttprequest结果放入一个字符串中
  详细解决方案

将XMLHttprequest结果放入一个字符串中

热度:19   发布时间:2023-06-05 15:56:50.0

我试图让我的URL数组通过JQuery .get函数运行,以将网站的源代码转换为该函数外部的一个字符串。 我的代码如下。

var URL = ["http://website.org", "http://anothersite.com"];

var array = URL.map(function(fetch)    {

      var get = $.get(fetch, function(sourcecode) {
           sourcecode = fetch;
      }

我需要sourcecode变量是数组中所有URL上的源代码的组合。

您需要将一个变量放置在函数外部,例如下面的data变量,然后使用+=附加到该变量:

var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch)    {
var data = null;

var get = $.get(fetch, function(sourcecode) {
     data += fetch;
}
}

像这样尝试

var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
   var data='';
   $.ajax({
      url:fetch,
      async:false,
      success : function(d){
         data=d;
      }
   });
   return data;
}).get();

由于您使用的是jQuery,因此我想可能是遍历数组的更好方法。

 var URL = ["http://website.org", "http://anothersite.com"]; var str = []; $.each(URL, function(index, fetch) { $.get(fetch, function(sourcecode) { str.push(sourcecode); // if you want an array }) }); str.join(''); // if you want a string console.log(str); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

  相关解决方案