5

我是阿贾克斯的新生

阿贾克斯

function ajaxFunction() {
  if(xmlhttp) { 
   var txtname = document.getElementById("txtname");
    xmlhttp.open("POST","Namelist",true);

    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("txtname=" + txtname.value); 
  }
}

function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       document.getElementById("message").innerHTML=xmlhttp.responseText;
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
}

jsp

<form name="fname" action="Namellist" method="post">

    Select Category :
    <select name="txtname" id="txtname">
     <option value="Hindu">Hindu</option>
     <option value="Muslim">Muslim</option>
     <option value="Christian">Christian</option>
    </select>
    <input type="button" value="Show" id="sh" onclick="ajaxFunction();">
    <div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
    </form>

小服务程序

String ct=null;  
ct=request.getParameter("txtname");
      Connection con=null;
      ResultSet rs=null;
      Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();

 out.println("name" + rs);
 **Here I have confusion,**

}
catch(Exception e)
{
    System.out.println(e);
}

我如何将 servlet 值显示为 jsp。请帮我?或者请提供一些好的教程链接。

4

3 回答 3

4

您必须进行以下更改:- 在 Servlet 中:- 将响应内容类型设置为:-response.setContentType("text/xml");在 servlet 的顶部。通过设置它,我们可以发送 XML 格式的响应,并在 JSP 上检索它时,我们将根据 XML 的标记名称获取它。

在 servlet 中执行您想要的任何操作...保存 ex- 的值

String uname=";
     uname="hello"; //some operation
    //create one XML string
    String sendThis="<?xml version='1.0'?>"
            +"<Maintag>"
            +"<Subtag>"
            +"<unameVal>"+uname+"</unameVal>"     
            +"</Subtag>"
            +"</Maintag>"
  out.print(sendThis);

现在我们将转到我们必须显示数据的 JSP 页面。

    function getXMLObject()  //XML OBJECT
        {
            var xmlHttp = false;
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
            }
            catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
                }
                catch (e2) {
                    xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
                }
            }
            if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
                xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
            }
            return xmlHttp;  // Mandatory Statement returning the ajax object created
        }
    var xmlhttp = new getXMLObject();   //xmlhttp holds the ajax object
        function ajaxFunction() {
            if(xmlhttp) {
                xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
                xmlhttp.onreadystatechange  = handleServerResponse;

                xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xmlhttp.send(null);
            }
        }
        function handleServerResponse() {
            if (xmlhttp.readyState == 4) {
                if(xmlhttp.status == 200) {
                   getVal();
                }
                else {
                    alert("Error during AJAX call. Please try again");
                }
            }
        }
       function getVal()
        {
             var xmlResp=xmlhttp.responseText;
             try{

                if(xmlResp.search("Maintag")>0 )
                {
               var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
                    var xx=x[0].getElementsByTagName("unameVal"); 
                    var recievedUname=xx[0].firstChild.nodeValue;
                   document.getElementById("message").innerText=recievedUname;//here 
                } 
                }catch(err2){
                    alert("Error in getting data"+err2);
                }
        }

到这里你就完成了。:)

于 2012-07-03T07:57:07.000 回答
2

1.在servlet代码中

PrintWriter output = response.getWriter();  
String result = "value";  
writer.write(result);  
writer.close()

2. 为什么不用jquery?
您可以替换您的代码 -

$.post('url', function(data) {  
$('#message1').html(data);  
});

查询帖子示例

于 2012-07-03T07:41:43.910 回答
2

可能摆脱困境但可能有用,而不是将所有 javascript 用于 Ajax 调用,而是使用一些 javascript 库,最好是 jQuery 来进行 Ajax 调用。

您使用的任何 javascript 库都将帮助您使代码简洁明了,还将帮助您保持跨浏览器的兼容性。

如果您打算自己编写所有 XHTTP 代码,您最终可能会花费大量时间来修复跨浏览器问题,并且您的代码将有很多 hack,而不是实际的业务逻辑。

此外,使用像 jQuery 这样的库也可以用更少的代码行来实现相同的效果。

希望有帮助。

于 2012-07-03T07:45:02.227 回答