参数值在Ajax中变为空?

时间:2014-05-23 06:45:09

标签: javascript html ajax jsp

我正在从html向jsp发送参数。当我试图在jsp中获取值时,我得到null值。我的代码有什么问题?请提出任何建议,

该值在警报

中的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>
    <%
%>

3 个答案:

答案 0 :(得分:3)

我忘了设置标题,现在它正在工作

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

答案 1 :(得分:0)

确保您所点击的网址有效。使用浏览器开发工具查看发送内容。

这对我有用:

您必须相应地提取值。 我想你也可以在你的网址中传递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");

答案 2 :(得分:0)

请在使用之前使用转义功能

  

xmlhttp.send(“cal =”+ escape(cal));

应该是

  

xmlhttp.send(“cal =”+ escape(cal));

作为excape编码特殊字符

http://www.w3schools.com/jsref/jsref_escape.asp

和服务器端解码它使用

Server.UrlDecode

http://www.aspsnippets.com/post/2009/02/01/AJAX-Calls-Using-JavaScript-And-XMLHTTP.aspx