【问题标题】:get email from html source code received via get ajax request从通过获取 ajax 请求收到的 html 源代码中获取电子邮件
【发布时间】:2013-07-24 19:09:57
【问题描述】:

以下代码从www.example.com 启动,获取www.example.com/example.html 的完整html 源代码并提示。

function process(){
    url = "http://www.example.com/example.html"
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function() {
    if (xhr.readyState == 4){
        alert(xhr.responseText)
        }
    }
    xhr.send();
}
process();

现在我要做的是从 html 源代码中获取电子邮件,如下所示:

<input type="hidden" id="email2" name="email2" value="example@example.com" />

通常,如果我在页面本身上,我会做一个简单的:

document.getElementById('email2').value

但在这种情况下,我如何简单地将电子邮件从包含所有 html 源代码的变量解析为变量:xhr.responseText

【问题讨论】:

    标签: javascript ajax parsing get


    【解决方案1】:

    你不能使用 getElementById.. 因为你只有一个字符串..但是你可以解析它

    alert(xhr.responseText.split('id="email2"')[1].split('value="')[1].split('"')[0])
    

    【讨论】:

    • 这行不通,因为您假设在那个 .html 页面中只有 1 行,至少有 500 行。
    • 我用该行替换了 alert(xhr.respondText.split) ,但没有收到任何警报。
    • 尝试...并告诉我输出 ....alert(xhr.responseText.split("email2")[1])
    • 我只是不确定。
    • 问题是 xhr.responseText 是未处理的源...可能与您在浏览器中看到的源不同...需要查看页面才能知道真正的问题...警报(xhr.responseText.split("email2")[1]) 未定义,那么您的 xhr.responseText 在任何地方都不包含 email2 ..
    【解决方案2】:

    您可以根据 xhr 调用的响应创建一个 HTML 文档,然后对其进行查询(使用 getElementById 或其他 DOM 函数)。

    请参阅How to create Document objects with JavaScript 了解如何创建新的 HTML 文档。

    【讨论】:

    • 这是一项相当肮脏的工作,我相信有一种更清洁的方法可以做到这一点。
    【解决方案3】:
    test2 = ""
    function process(){
        url = "http://www.example.com/example.html"
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.onreadystatechange = function() {
        if (xhr.readyState == 4){
            test2 = xhr.responseText.split('id="email2"')[1].split('value="')[1].split('"')[0]
        process2();
        //do stuff here
            }
        }
        xhr.send();
    }
    process();
    
    function process2(){
        // or do stuff here
        alert(test2);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2019-03-30
      • 2014-04-25
      相关资源
      最近更新 更多