2016-05-12 43 views
0

尝试解析ajax请求的单词“function”并将最后一个匹配的字符存储在数组中。唯一错误的JSLint被返回是使用Javascript解析网页(涉及ajax和jquery)

意外( '空间')

结合这一说法与之前的 '变种' 语句,

既不我相信应该影响代码是否被执行。任何帮助表示赞赏。

/*jslint browser: true*/ 
/*global $, jQuery, alert*/ 
$(document).ready(function() { 
    "use strict"; 


    //retrieve page 
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET",  "https://abs.twimg.com/c/swift/en/init.27d18bf5a2b7d3e5fbcdbb86f85e7a534b11f06b.js", true); 
    xhr.responseType = "text"; 
    xhr.send(); 
    xhr.onload = function() { 

     //set variables to be compared 
     var page = xhr.responseText; 
     var word = "function"; 

     //page and word locations 
     var i = 0; 
     var n = 0; 
     var page_loc = page[i];    
     var word_loc = word[n]; 

     //matched result storage 
     var chain = [""]; 

     // compare 
     while (n < word.length - 1) { 
      if (page_loc === word_loc) { 
       n = n + 1; 
       i = i + 1; 
       console.log(i); 
      } else { 
       i = i + 1; 
      } 
     } 

     //place matched result 
     chain.push(page_loc); 
     console.log(chain); 
    }; 
}); 
+0

_page单词“功能”,并存储在一个array_最后,匹配的是什么最后的匹配字符意味着什么?你想只是检查给定页面是否存在“函数”并返回它的最后一个字符? –

+0

对不起,我不是很清楚我只是意味着字符串即时搜索的最后一个字符,所以在这种情况下,“功能”中的“n”。 – magnavan

回答

0

所以关于你的评论和问题。

如果您只想检查给定的字符串是否存在于响应中,则不需要遍历该字符串,您可以使用内置函数indexOf()或更新的浏览器includes()

因此,代码看起来如下:

$(document).ready(function() { 
    "use strict"; 

    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", "https://abs.twimg.com/c/swift/en/init.27d18bf5a2b7d3e5fbcdbb86f85e7a534b11f06b.js", true); 
    xhr.responseType = "text"; 
    xhr.onload = function() { 
    var page = xhr.responseText; 
    var word = "function"; 
    if (page.indexOf(word) !== -1) 
     console.log([word[word.length-1]]); 
    }; 
    xhr.send(); 
}); 
+0

“首先,您必须在发送send()之前添加侦听器,” - 不正确。由于JavaScript是单线程的,在分配它和调用send()完成的函数之前,事件处理程序是无法搜索的。 – Quentin

+0

很高兴知道,删除! –