JavaScript保存来自ajax请求的数据

JavaScript Saving data from an ajax request

本文关键字:请求 数据 ajax 保存 JavaScript      更新时间:2023-09-26

挑战:在URL1(随机维基百科页面)上,向URL2(100个最常见的单词维基百科页面)发出ajax请求,从返回的数据中格式化一个列表,以便稍后使用。

我必须在"URL1"上从控制台运行此程序示例:

  1. 导航到URL1
  2. 打开控制台
  3. 粘贴代码
  4. 点击回车

到目前为止,我已经能够在URL1上使用以下内容获取整个html源代码:

$.ajax({
    url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
    type: 'GET',
    dataType: 'html',
    success: function (response) {
        console.log(response); // works as expected (returns all html)
    }
});

我可以在控制台中看到整个HTML源代码——然后我去URL2了解如何获取和格式化我需要的内容,我可以使用

var array = $.map($('.wikitable tr'),function(val,i){
        var obj = {};
        obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
        return obj;
    });
console.log(JSON.stringify(array));

这就是我的问题所在——将两个结合起来

$.ajax({
url:'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type:'GET',
dataType:'html',
success: function(data){
    // returns correct table data from URL2 while on URL2 -- issue while running from URL1
    var array = $.map($('.wikitable tr'),function(val,i){
        var obj = {};
        obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
        return obj;
        });
console.log(JSON.stringify(array));
    };
});

我猜这是因为我想要映射的HTML现在是一个字符串,而我的数组正在当前页面上寻找它当然找不到的HTML元素。

感谢

这里简单修复!你说得对,它并没有解析你返回的html,所以只需告诉jQuery将其转换为一个可以使用$(data)的对象,并使用它来查找你需要的内容。

从本质上讲,您的"文档"现在变成了$(data),您将使用它作为所有查询的来源。

 $.ajax({
   url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
   type: 'GET',
   dataType: 'html',
   success: function(data) {
     var myVar = data;
     Names = $.map($(myVar).find('.wikitable tr'), function(el, index) {
       return $(el).find('td:last').text()
     });
     console.log(Names);
   }
 });