【问题标题】:POST HTML via XMLHttpRequest通过 XMLHttpRequest 发布 HTML
【发布时间】:2011-04-22 00:41:25
【问题描述】:

我正在尝试通过 XMLHttpRequest 发布页面正文

var params = "type=search" + "&content="+encodeURIComponent(document.getElementsByTagName("body")[0].innerHTML);
xmlhttp.open("POST", "/service/p.aspx", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length); 
xmlhttp.send(params);

【问题讨论】:

    标签: javascript ajax post


    【解决方案1】:

    以下内容在 Firefox 和 IE8 中适用于我:

    <html>
        <body>
            <script type="text/javascript">
    // MAYBE FORGOT THIS PART?
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4)
        {
            document.write(xmlhttp.responseText);
        }
    }
    
    // THIS PART IS EXACTLY LIKE YOURS
    var params = "type=search" + "&content="+encodeURIComponent(document.getElementsByTagName("body")[0].innerHTML);
    xmlhttp.open("POST", "/service/p.aspx", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length); 
    xmlhttp.send(params);
            </script>
        </body>
    </html>
    

    也许您只是忘记声明xmlhttp 并为异步状态回调添加监听器?


    此外,有关以跨浏览器方式获取 XMLHttpRequest 对象的更多信息,请参阅 this SO question


    这是通过 Firefox 中的 FireBug 在 POST 请求中发送的内容:

    type=search&content=%0A%20%20%20%20%20%20%20%20%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%2F%2F%20MAYBE%20FORGOT%20THIS%20PART%3F%0Avar%20xmlhttp%20%3D%20new%20XMLHttpRequest()%3B%0Axmlhttp.onreadystatechange%3Dfunction()%0A%7B%0A%20%20%20%20if%20(xmlhttp.readyState%3D%3D4)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20document.write(xmlhttp.responseText)%3B%0A%20%20%20%20%7D%0A%7D%0A%0A%2F%2F%20THIS%20PART%20IS%20EXACTLY%20LIKE%20YOURS%0Avar%20params%20%3D%20%22type%3Dsearch%22%20%2B%20%22%26content%3D%22%2BencodeURIComponent(document.getElementsByTagName(%22body%22)%5B0%5D.innerHTML)%3B%0Axmlhttp.open(%22POST%22%2C%20%22%2Fservice%2Fp.aspx%22%2C%20true)%3B%0Axmlhttp.setRequestHeader(%22Content-type%22%2C%20%22application%2Fx-www-form-urlencoded%22)%3B%0Axmlhttp.setRequestHeader(%22Content-length%22%2C%20params.length)%3B%20%0Axmlhttp.send(params)%3B%0A%20%20%20%20%20%20%20%20%3C%2Fscript%3E
    

    所以你有type 等于searchcontent,这是上面HTML 的HTTP 编码body,完全按照编程。所以它似乎按预期工作......

    【讨论】:

    • 你好 jdmical,感谢你的帮助,我声明 xmlhttp 很抱歉没有将它包含在我的问题中。我无法发送 html 页面正文内容,但我可以发送任何其他内容。谢谢
    • @fligant 我将实际的 POST 消息添加到答案中。请检查。
    • 谢谢你 jsmical 它的工作我不知道为什么!但它有效:) 谢谢你的帮助
    猜你喜欢
    • 2013-09-06
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    相关资源
    最近更新 更多