且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一个简单的Ajax与JSP示例

更新时间:2022-10-15 23:34:26

您正在做错误的configuration_page.jsp文件。 这里,在这个文件中,函数loadXMLDoc()把的2号线应该是这样的:

 无功配置= document.getElementsByName('configselect')值;
 

因为你只声明了名称属性在<选择> 标记。所以,你应该通过名字得到这个元素。

在纠正这个,它将运行没有任何JavaScript错误

I am trying to learn AJAX with JSP and I have written the following code. This does not seem to be working. Kindly help:

This is my configuration_page.jsp

    <html>
     <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <title>JSP Page</title>
     <script type="text/javascript">

      function loadXMLDoc()
      {
        var xmlhttp;
        var config=document.getElementById('configselect').value;
        var url="get_configuration.jsp";
        if (window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest();
        }
        else
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            }
        }

        xmlhttp.open("GET", url, true);
        xmlhttp.send();
}
</script>        

</head>

<body>
  <h2 align="center">Saved Configurations</h2>
   Choose a configuration to run: 
  <select name="configselect" width="10">
    <option selected value="select">select</option>
    <option value="Config1">config1</option>
    <option value="Config2">config2</option>
    <option value="Config3">config3</option>
  </select> 
  <button type="button" onclick='loadXMLDoc()'> Submit </button>
  <div id="myDiv">
    <h4>Get data here</h4>
  </div>
 </body>
</html>

This is my get_configuration.jsp which I am trying to access from the AJAX code above:

<html>
  <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>JSP Page</title>

  </head>
  <body>

    <h4>Mee..</h4> 
  </body>
</html>

You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:

var config=document.getElementsByName('configselect').value;

because you have declared only the name attribute in your <select> tag. So you should get this element by name.

After correcting this, it will run without any JavaScript error