繁体   English   中英

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

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

尝试为一个单词“ function”解析一个ajax请求页面,并将最后匹配的字符存储在一个数组中。 JSLint返回的唯一错误是

意外的(“空格”)

将此语句与先前的“ var”语句结合起来,

我认为这两个都不影响代码是否执行。 任何帮助表示赞赏。

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

因此,关于您的评论和问题。

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

因此,代码如下所示:

$(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