2012-06-25 30 views
0
I'm using XMLHttpRequest POST to send data to a jsp. But the jsp is not invoked. Here is my code. 

的JS方法被调用点击一个按钮XMLHttpRequest的POST调用不工作

<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 is没有被调用,但我得到了OK警报。如果我尝试http get而不是post并将参数追加到uri,它就会起作用。我正在使用IE8。

请帮忙。

回答

0

您是否尝试过使用jQuery为了让您的帖子?

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

使用jQuery也将使您的代码跨浏览器兼容,并且该链接上的示例更容易遵循。还有其他的jQuery options,如果你想更好地控制请求。我强烈推荐它 - 对于这样的任务和其他许多任务,它会让你的生活变得更简单,让你的编码更加愉快!

+0

是的,我能够创建一个功能齐全的jquery ajax xmlhttprequest,但是他们的api没有他们的服务器上的Allow-Control-Access-Origin设置,用于'安全原因'。 – JosephMCasey

+0

如果您正在点击的服务支持JSONP,它将解决此问题。如果它不支持它,也许它应该。另见http://stackoverflow.com/questions/20518653/jsonp-cross-origin-error-no-access-control-allow-origin-header-is-present – Shawn