JQuery開發詳解(二)

JQuery跨域訪問
模擬方法:修改C:\Windows\System32\drivers\etc\hosts文件

準備工作一:後臺接收參數jsoncallback,封裝返回的JSON數據

package cn.zzu.wcj.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns="/EchoServlet")
public class EchoServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
         //請求和響應都要設置編碼才能解決亂碼 
           req.setCharacterEncoding("UTF-8") ;
           resp.setCharacterEncoding("UTF-8");
           resp.setContentType("text/html");
           String jsonpcallback = req.getParameter("jsonpcallback") ;   //控制層接收JQuery規定跨域訪問的參數
           String content="{\"members\":[{\"name\":\"張三\",\"age\":\"30\"}]}"  ;   //返回內容
           System.out.println("msg="+req.getParameter("msg"));
           System.out.println("eid="+req.getParameter("eid"));
           resp.getWriter().print(jsonpcallback+"("+content+")");    //最終返回的信息 
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
            this.doGet(req, resp);
    }

}

準備工作二:.ajax/ .getJSON配置好返回數據類型

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSONP詳解</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/jquery/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
     $(function(){
              $("#sendBtn").on("click",function(){
                     var msgValue=$("#msg").val()   ;    //取得信息  
                     $.ajax({
                             url : "http://www.pp.com/JQueryCase/EchoServlet"  ,                      //Ajax提交路徑  
                             data : {                                             //傳遞的參數
                                 "msg" : msgValue ,
                                 "eid"   : 666    ,
                             }    ,
                             type : "post"   ,                           //發送類型
                             dataType : "jsonp"   ,                  //返回值類型 
                             jsonp :  "jsonpcallback" ,    
                             success : function(json){     //回調函數
                                  $("#contentDiv").append("<p>姓名:"+json.members[0].name+",年齡:"+json.members[0].age+"</p>")  ;
                             }   ,
                             error :function(){    //異常處理函數 
                                   alert("對不起,操作出現了異常,無法連接!");
                             }
                     });
              })   ;
     });
</script>
</head>
<body>
     請輸入內容:<input type="text" name="msg" id="msg">
        <input type="button" value="發送" id="sendBtn">
        <div id="contentDiv"></div>
</body>
</html>

注意dataType ,jsonp的配置

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSONP詳解</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/jquery/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
     $(function(){
              $("#sendBtn").on("click",function(){
                     var msgValue=$("#msg").val()   ;    //取得信息  
                     $.getJSON(  "http://www.pp.com/JQueryCase/EchoServlet?jsonpcallback=?",{"msg":msgValue,"eid":888},function(json){   
                         $("#contentDiv").append("<p>姓名:"+json.members[0].name+",年齡:"+json.members[0].age+"</p>")  ;
                     },"json")  ;
              })   ;
     });
</script>
</head>
<body>
     請輸入內容:<input type="text" name="msg" id="msg">
        <input type="button" value="發送" id="sendBtn">
        <div id="contentDiv"></div>
</body>
</html>

使用$.getJSON可以簡化獲取JSONP,注意:需要傳參:jsonpcallback=?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章