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。
请帮忙。
是的,我能够创建一个功能齐全的jquery ajax xmlhttprequest,但是他们的api没有他们的服务器上的Allow-Control-Access-Origin设置,用于'安全原因'。 – JosephMCasey
如果您正在点击的服务支持JSONP,它将解决此问题。如果它不支持它,也许它应该。另见http://stackoverflow.com/questions/20518653/jsonp-cross-origin-error-no-access-control-allow-origin-header-is-present – Shawn