jquery用post方式异步调用jsp,jsp取不到参数。
代码:
test.html:
<script type="text/javascript" src="js/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "post",
url: "test.jsp",
datatype: "json",
contentType: "application/json",
data:"{id:1234}",
success: function(result){
alert(result);
}
});
});
</script>
服务器端的test.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String id=request.getParameter("id");
out.print("Parameter is :"+id);
%>
不知道什么原因,测试结果显示为:Parameter is :null
如果将将test.html修改一下,下面两种写法都可以接收到参数
方式一:
$.ajax({
type: "get",
url: "test.jsp",
datatype: "json",
contentType: "application/json",
data:"id=1234",
success: function(result){
alert(result);
}
});
方式二:
$.ajax({
type: "POST",
url: "test.jsp?id=1234",
datatype: "json",
contentType: "application/json",
data:"{}",
success: function(result){
alert(result);
}
});
这是为什么呢?有什么办法在POST方式下,用data:"{}"传参数给jsp呢?
追问:这不是一样吗?只是我换行写,你写在一行中。查看jquery源码可以发现,$.post最终还是调用的$.ajax。测试过,没用!谢谢!有点眉目了,
$.post("test.jsp",{id:1234},function(data){alert(data);});可以执行,但1234如果是一个变量,怎么写进去呢?
答案:直接用jquery封装的$.post(url,{id:1234,name:"jim".......},function(data,status){});
其他:json形式的ajax注意data传的不是字符串,要这样写:
data:{id:1234}
上一个:在XSL文件中做图片切换特效,需要加入jsp语句,请问该怎么加入?
下一个:如何用JSP获取SQL2000中某个表的一个字段,,我这张表里有14个字段,我只要取出某个字段在页面里进行操作