簡體   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