2014-05-23 29 views
1

我從html發送參數到jsp。當我試圖在jsp中獲取值時,我得到空值。我的代碼有什麼問題?任何建議請參數值在Ajax中變爲空?

值在Java腳本打印在警報

HTML:

<!DOCTYPE html> 
<html> 
<head> 
<script> 
function load() 
{ 
var cal=document.getElementById('course').value; 
alert(cal); // Value is printing here 
var xmlhttp; 
if (window.XMLHttpRequest) 
    { 
    xmlhttp=new XMLHttpRequest(); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText; // I am gtting response but value is null 
    } 
    } 
xmlhttp.open("POST","LoadAjax.jsp",true); 
xmlhttp.send("cal="+cal); 
} 
</script> 
</head> 
<body> 
<div id="myDiv"><h2>Submit</h2></div> 
<input type = "text" id = "course" name = "course"> 
<button type="button" onclick="load()">Change Content</button> 
</body> 
</html> 

我的JSP代碼如下,我能夠發送響應,但唯一的問題是我沒有收到價值

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%> 
    <%@ page import ="java.sql.*" %> 
<%@ page import ="javax.sql.*" %> 

<% 
String sn=request.getParameter("cal"); 
System.out.println(sn); 
    %> 
    <select class="input_dropdown01" name="ccode" id="Div1" onchange="load();" > 
    <option selected="selected">Select</option> 
    <option value="<%out.println(sn);%>" ><%out.println(sn);%></option> 
    </select> 
    <% 
%> 
+0

您必須使用Jquery。這是非常容易和易於編碼 – xrcwrn

+0

使用'<%=sn%>'而不是'<%out.println(sn);%>'這是分配。 – Braj

+0

@Braj你的第一個表情是無效的,應該是'<%=sn%>'而不是 –

回答

0

請確保您打的URL是有效的。使用瀏覽器開發工具來查看發送的內容。

這個工作對我來說:

您必須相應地拉動值。 我想你也可以在你的URL傳遞CAL作爲查詢字符串

var obj = {}; 
    obj.cal = "Your value here"; 
    var postBody = ""; 
    postBody = JSON.stringify(obj); 

    var url = "server_url"; 

    xmlHttp.open("POST", url, true); 
    xmlHttp.setRequestHeader("Accept", "application/json"); 
    xmlHttp.setRequestHeader("Content-type", "application/json"); 
    xmlHttp.send(postBody); 


OR 
     var url = "server_url"; 
     xmlHttp.open("POST", url, true); 
     xmlHttp.setRequestHeader("Accept", "application/json"); 
     xmlHttp.setRequestHeader("Content-type", "application/json"); 
     xmlHttp.send("Your_data_here"); 
3

我忘記了設置的標頭,現在它正在工作

xmlhttp.open("POST","LoadAjax.jsp",true); 
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
xmlhttp.send("cal= "+cal); 
+0

似乎是一個愚蠢的錯誤@manju。應該知道這一點 –