2012-01-18 76 views
9

我想學習與JSP的AJAX,我寫了下面的代碼。這似乎沒有工作。請幫助:一個簡單的AJAX與JSP的例子

這是我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> 

這是我get_configuration.jsp其中我從上面的AJAX代碼試圖訪問:

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

    </head> 
    <body> 

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

如果運行的話,不應該包含'','','' 。它應該包含'

'。幫你一個忙,並使用jQuery。 – 2012-01-18 08:58:54

+0

還建議使用jQuery:它具有更簡單的語法和交叉瀏覽器可移植性。 – Dims 2012-01-18 09:27:10

回答

1

您在「configuration_page.jsp」文件中犯了錯誤。 這裏,在這個文件中,函數loadXMLDoc()把的2號線應該是這樣的:

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

,因爲你已經宣佈只在您的<select>標籤name屬性。所以你應該得到這個元素的名字。

更正此之後,它會不get_configuration.jsp的結果作爲一個div的內容有任何JavaScript錯誤

12

我已經使用jQuery AJAX來發出AJAX請求。

檢查下面的代碼:

<html> 
<head> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $('#call').click(function() 
      { 
       $.ajax({ 
        type: "post", 
        url: "testme", //this is my servlet 
        data: "input=" +$('#ip').val()+"&output="+$('#op').val(), 
        success: function(msg){  
          $('#output').append(msg); 
        } 
       }); 
      }); 

     }); 
    </script> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>JSP Page</title> 
</head> 
<body> 
    input:<input id="ip" type="text" name="" value="" /><br></br> 
    output:<input id="op" type="text" name="" value="" /><br></br> 
    <input type="button" value="Call Servlet" name="Call Servlet" id="call"/> 
    <div id="output"></div> 
</body> 

0

loadXMLDoc JS函數應該返回false,否則會導致回發。