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;
}