2010-05-04 39 views
0

在JSP頁面中我已經寫:如何從JSP獲取Servlet中的JSON對象?

var sel = document.getElementById("Wimax"); 
var ip = sel.options[sel.selectedIndex].value; 
var param; 
var url = 'ConfigurationServlet?ActionID=Configuration_Physical_Get'; 
httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
httpRequest.open("POST", url, true); 
httpRequest.onreadystatechange = handler(){ 
if (httpRequest.readyState == 4) { 
if (httpRequest.status == 200) { 
param = 'ip='+ip; 
param += 'mmv='+mmv; 
param += "tab="+tab; 
}}; 
httpRequest.send(param); 

我想在我的ConfigurationServlet這個param變量。任何人都可以告訴我如何讓這個json對象在servlet中?

更新:我改變了我的發言,現在它顯示狀態碼200

var index = document.getElementById("Wimax").selectedIndex; 
var ip = document.getElementById("Wimax").options[index].text; 
httpReq = GetXmlHttpObject(); 
alert(httpReq); 
var param = "ip=" + ip; 
param += "&mmv=" + mmv; 
param += "&tab=" + tab; 
alert("param "+param); 
var url="http://localhost:8080/WiMaxNM/ConfigurationServlet?ActionID=Configuration_Physical_Get"; 
url = url+"?"+param; 
httpReq.open("GET",url,true); 
alert("httpReq "+httpReq); 
httpReq.onreadystatechange = handler; 
httpReq.send(null); 

但新的問題又發生。控制根本不會按照url中指定的servlet操作ID進行。請告訴我這裏有什麼問題。

回答

0

處理程序中的代碼將只在請求發送後才被調用。在此之前,您需要填寫param。您還需要通過&聯合分開單獨的參數。

因此,例如,

// ... 
httpRequest.onreadystatechange = handler() { 
    // Write code here which should be executed when the request state has changed. 
    if (httpRequest.readyState == 4) { 
     // Write code here which should be executed when the request is completed. 
     if (httpRequest.status == 200) { 
      // Write code here which should be executed when the request is succesful. 
     } 
    } 
}; 

param = 'ip=' + ip; 
param += '&mmv=' + mmv; 
param += "&tab=" + tab; 
httpRequest.send(param); 

然後你可以在servlet中通過HttpServletRequest#getParameter()的方式訪問它們。


這就是說,Ajax代碼,你貼有將在所有四個其他主要化網頁瀏覽器世界意識到在Microsoft Internet Explorer只工作,不。換句話說,你的Javascript代碼不適用於世界上大約一半的人。

我建議看看jQuery,以減少所有冗長的工作並消除crossbrowser兼容性問題。你所有的代碼都可以很容易地被

var params = { 
    ip: $("Wimax").val(); 
    mmv: mmv, 
    tab: tab 
}; 
$.post('ConfigurationServlet?ActionID=Configuration_Physical_Get', params); 

而且仍然可以在所有web瀏覽器中運行!

更新:根據您的更新,最終的URL顯然是錯誤的。 ?表示查詢字符串的開始。您的網址中已經有一個。您應該使用&來鏈接查詢字符串中的參數。即

url = url + "&" + param; 
+0

對於使用HttpServletRequest#getParameter(),我必須給隱藏id param然後document.form id.submit。而不是我不能通過ActiveXObject()的對象得到它? – divi 2010-05-04 12:05:53

+0

我不明白你的意思。請直接爲你自己解決。在w3schools.com是學習Ajax平凡的很好的教程,在Coreservlets.com上是學習Servlet平凡的很好的教程。 – BalusC 2010-05-04 12:18:23

+0

好吧BalusC.but還有一個問題,我有。我的應用程序顯示狀態代碼= 500(內部服務器錯誤)。你能爲此建議我嗎? – divi 2010-05-05 10:53:15