0

やあみんな、これは私を絶対に狂わせているので、私はこのサイトの専門家にそれを行う方法を知っているかどうかを尋ねたいと思いました=)

Webページの要素を読み取ることができるJavaScriptコードを作成しようとしています(たとえば、最初の段落は何と言っていますか?)。これが私がこれまでに持っているものですが、それは機能せず、理由を理解できません:

<script type="text/javascript">
<!--
var req;
// handle onreadystatechange event of req object
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            //document.write(req.responseText);
            alert("done loading");

            var responseDoc = new DOMParser().parseFromString(req.responseText, "text/xml");
            alert(responseDoc.evaluate("//title",responseDoc,null,
                        XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
         } 
         else {
            document.write("<error>could not load page</error>");
         }
    }
}

req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.apple.com", true);
req.send(null);
// -->

表示され続けるアラートは「null」であり、その理由がわかりません。何か案は?

4

1 に答える 1

0

This may be due to cross domain restriction... unless you're hosting your web page on apple.com. :) You could also use jQuery and avoid writing all that out and/or dealing with any common possible cross-browser XML loading/parsing issues. http://api.jquery.com/category/ajax/

Update: Looks like it may have something to do with the source web site's Content-Type or something similar... For example, this code seems to work... (Notice the domain loaded...)


var req;
// handle onreadystatechange event of req object
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"

        if (req.status == 200) {
            //document.write(req.responseText);
            //alert("done loading");
            //alert(req.responseText);

            var responseDoc = new DOMParser();
            var xmlText = responseDoc.parseFromString(req.responseText, "text/xml");
            try{
              alert(xmlText.evaluate("//title",xmlText,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
            }catch(e){
              alert("error");
            }
         } 
         else {
            document.write("could not load page");
         }
    }
}

req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.jquery.com", true);
req.send(null);

I also tried loading espn.com and google.com, and noticed they both have "Content-Encoding:gzip" so maybe that's the issue, just guessing though.

于 2011-03-11T03:20:23.110 に答える