1. 程式人生 > >ajax 異步請求,json前臺後臺交互

ajax 異步請求,json前臺後臺交互

ioe exceptio servlet set 後臺 通過 int oid function

直接上例子!

第一例:

1.導入json的相關jar包

2.後臺servlet代碼

public class ajaxtest extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
     //上面是處理亂碼的 String[] str
= {"張三","李四","王五"}; //最普通的json數組結構 JSONArray json = JSONArray.fromObject(str); //string轉json結構 PrintWriter out = response.getWriter();   out.print(json); //response 將json輸出到客戶端。
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

前端jsp頁面

<script type="text/javascript"
    src="http://libs.cdnjs.net/jquery/3.2.1/jquery.js"></script>

<script type="text/javascript">
$(document).ready(function(){
  $("#b01").click(function(){
      $.getJSON("${pageContext.request.contextPath}/ajaxtest",function(result){
          $.each(result,function(i,field){
              $(
"#myDiv").append(field+":"); }); }); }); }); </script> </head> <body> <div id="myDiv"><h2>通過 AJAX 改變文本</h2></div> <button id="b01" type="button">改變內容</button>

點擊按鈕的結果:張三:李四:王五。

----------------------------------------------------------

第二例

ajax 異步請求,json前臺後臺交互