我想将 JSON 转换后的数据(html 代码)发送到requestGet
Servlet。我的代码在将 POST 请求发送到 servlet 时是绝对正确的,但是在将字符串转换为 JSON 时出现错误。
我正在使用myeclipse,当我运行此代码时,它会显示
“JSON 未定义”
但是当我将它保存为 HTML 并在 FF 上运行时,它既不显示任何错误也不向 servlet 发送任何请求。请建议我的方法对于通过 POST 方法将 JSON 文本发送到 servlet 是否正确。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<SCRIPT language="javascript">
var counter=0;
var controls=new Array();
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
element.id=type+counter;
controls[counter]=element.id;
counter++;
var foo = document.getElementById("fooBar");
foo.appendChild(element);
}
function save(){
var data="";
var formTitle="Form1";
var method="post";
data="<HTML><HEAD><TITLE>"+formTitle+"</TITLE></HEAD><BODY><FORM METHOD="+method+"/>";
for(i=0;i<controls.length;i++){
var element=document.getElementById(controls[i]);
data+="<INPUT type=button id="+element.id+" value="+element.getAttribute("value")+"/>";
}
data+="</FORM></BODY></HTML>";
alert("Data::"+data);
DoSelectRecommendation(data);
}
/*
* code for sending request to the servlet.
*/
$(function() {
var frm = $(document.myform);
var dat = JSON.stringify(frm.serializeArray());
alert("I am about to POST this:\n\n" + dat);
$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
});
var req;
function DoSelectRecommendation(Text) {
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
var url="http://localhost:8080/TestForJsp/requestGet";
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send(Text);
req.onreadystatechange = inserter;
}
function inserter() {
if (req.readyState == 4) {
if (req.status == 200) {
var msg = req.responseText;
alert("msg = "+msg);
if (msg == "") {
document.getElementById("msg1").innerHTML = "<div style=\"color:red\">"+"COS NIE TAK"+"</div>";
//document.getElementById("msg1").value = "blabla";
}
else
document.getElementById("msg1").innerHTML = "<div style=\"color:red\">"+msg+"</div>";
//document.getElementById("msg1").value = "COOOO JEST";
}
}