jquery 异步请求例子
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<script type="text/javascript" src="<%=request.getContextPath()%>/personal/xhu/js/jquery-1.8.0.min.js"></script>
<script>
//Jquery Ajax处理跳转
function doAjax() {
$.ajax( {
url : "cw_bm_sqcl.jsp",
dataType : "text", //传参的数据类型
type : "post", //传参方式,get 或post
data : {
txt : "这是变量值" //传过去的参数,格式为 变量名:变量值
},
error : function(msg) { //若Ajax处理失败后返回的信息
alert("Ajax跳转处理失败");
},
success : function(text) { //若Ajax处理成功后返回的信息
document.getElementById("txt").innerHTML = "Ajax处理已成功,返回的信息:" + text;
alert("Ajax处理已成功");
}
});
}
</script>
<span id="txt" style="color: green"></span><br>
<input type="button" name="doAjax" value="Ajax动态处理" onclick="doAjax()">
cw_bm_sqcl.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String txt = request.getParameter("txt");
out.println(txt);
%>
jsp返回JSON方法
//JSon字符串转JSon对象;使JSP页面直接返回JSON对象
//使用示例>> 在JSP代码里的最后一行加入 <% renderJson(response, json.toString()); %> 这段代码
public static String renderJson(HttpServletResponse response, String content){
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
java.io.PrintWriter pw = null;
try{
pw = response.getWriter();
pw.write(content);
}catch (Exception e){
//
}finally{
pw.close();
}
return null;
}