使用JSONP实现跨域请求

daiqinge 2013-12-19

html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
 <head>
     <title>使用JSONP解决跨域请求</title>
      <script type="text/javascript" src="http://192.168.118.64:8989/htmlunit/jquery-1.7.1.min.js"></script>
      <script type="text/javascript">
     jQuery(document).ready(function(){ 
        $.ajax({
             type: "get",
             async: false,
             url: "http://192.168.118.64:8989/htmlunit/jsonp/ts.json?code=CA1998",
             dataType: "jsonp",
             jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
             success: function(json){
                 //alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');
                 $("#price").text(json.price);
                 $("#tickets").text(json.tickets);
             },
             error: function(){
                 alert('fail');
             }
         });
     });
     </script>
     </head>
  <body>
  
  		<div>
  			<h3>机票信息</h3>
  			<div>票价:<span id="price">查询中...</span></div>
  			<div>余票:<span id="tickets">查询中...</span></div>
  		</div>
  </body>
 </html>

服务器代码:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * 这个是个JSONP的演示的例子,用于解决跨域请求的问吧。
 * @author hc24
 *
 */
public class TestServlet extends HttpServlet {

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		/* 得到回调的方法名 */
		String methodName=request.getParameter("callback");
		
		/* 得到参数 */
		String flightNo=request.getParameter("code");
		
		/*下面应该是根据参数查询价格和座位数 */
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		float price=1780.00f;
		int tickets=5;
		
		StringBuilder sb=new StringBuilder();
		sb.append(methodName+"({");
		sb.append("code:\""+flightNo+"\",");
		sb.append("price:"+price+",");
		sb.append("tickets:"+tickets+"");
		sb.append("})");
		
		out.write(sb.toString());//返回到客户端
		
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

相关推荐