简体   繁体   English

使用Java脚本解析网页(涉及到ajax和jquery)

[英]Parsing a web page using Javascript (ajax and jquery involved)

Trying to parse an ajax requested page for the word "function" and store the last matched character in an array. 尝试为一个单词“ function”解析一个ajax请求页面,并将最后匹配的字符存储在一个数组中。 The only errors JSLint is returning are JSLint返回的唯一错误是

unexpected ('space') 意外的(“空格”)

and

Combine this statement with the previous 'var' statement, 将此语句与先前的“ var”语句结合起来,

neither of which I believe should effect whether or not the code is executed. 我认为这两个都不影响代码是否执行。 Any help is appreciated. 任何帮助表示赞赏。

/*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);
    };
});

So regarding your comment and question. 因此,关于您的评论和问题。

You don't need to iterate over that string, if you only want to check whether a given string is present in a response, you can use a built-in function indexOf() or in newer browsers includes() . 您不需要遍历该字符串,如果只想检查响应中是否存在给定的字符串,则可以使用内置函数indexOf()或在较新的浏览器include()中使用

So the code would look as follow: 因此,代码如下所示:

$(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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM