【问题标题】:XMLHttpRequest POST call not workingXMLHttpRequest POST 调用不起作用
【发布时间】:2012-06-25 13:42:44
【问题描述】:
I'm using XMLHttpRequest POST to send data to a jsp. But the jsp is not invoked. Here is my code.

按钮点击时调用JS方法

<form action="">
<div><input type="button" value="POST DATA"
    onclick=test();
/></div></form>

JS 方法做一个 http POST -

<script>
function test() {
        var xmlHttpRequest = new ActiveXObject('Msxml2.XMLHTTP');
        xmlHttpRequest.open("post",
                "http://localhost:4502/content/myTest.html", true);
        xmlHttpRequest.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded");
        xmlHttpRequest.onreadystatechange = function() {
            getResult(xmlHttpRequest)
        };
        try {
            xmlHttpRequest.send("username=john");
        } catch (e) {
            alert("error" + e);
        }
    }
    function getResult(xmlHttpRequest) {
        if (xmlHttpRequest.readyState == 4) {
            if (xmlHttpRequest.status == 200) {
                alert("ok");
            } else {
                alert("error" + xmlHttpRequest.status);
            }
        }
    }
</script>

myTest.jsp 将 POST 请求写入文本文件 -

  <%
    FileOutputStream fos = new FileOutputStream("D:/test.txt");
    PrintWriter pw = new PrintWriter(fos);
    pw.println(request.getParameter("username"));
    %>

myTest.jsp 没有被调用,但我得到了 OK 警报。如果我尝试使用 http get 而不是 post 并将参数附加到 uri,它可以工作。我用的是 IE8。

请帮忙。

【问题讨论】:

    标签: jquery ajax post xmlhttprequest aem


    【解决方案1】:

    您是否尝试过使用 jQuery 来发帖?

    在使用之前,您需要在页面中包含 jQuery 库。

    使用 jQuery 还可以使您的代码跨浏览器兼容,并且该链接上的示例更易于理解。如果您还想对请求进行更多控制,还有其他 jQuery options。我强烈推荐它——对于像这样的任务和许多其他任务,它会让你的生活更简单,你的编码更愉快!

    【讨论】:

    • 是的,我能够创建一个功能齐全的 jquery ajax xmlhttprequest,但是出于“安全原因”,他们的 api 在他们的服务器上没有设置 Allow-Control-Access-Origin。
    • 如果您访问的服务支持 JSONP 将解决此问题。如果它不支持它,也许它应该。另见stackoverflow.com/questions/20518653/…
    猜你喜欢
    • 2017-11-27
    • 2018-04-11
    • 2013-08-04
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多