1. 程式人生 > >jsonp(跨域請求)案例

jsonp(跨域請求)案例

jsonp案例:

前端:

<script type="text/javascript">
    function getMatchCountry(){
         var key = $.trim($(".global_search_input").val());
         if (key==''){
            $(".search_list").hide();
            return
          };
$.ajax({
             type: "get",
             async: false,
             url: "http://localhost:9091/leading/pageTopAction.aspx?method=match_country_lua&l="+_navLanguage+"&q="+key,
             dataType: "jsonp",
             jsonp: "callback",
             jsonpCallback:"flightHandler",
             success: function(data){
                 $(".search_list").empty();
                 var ht = "";
               $.each(data, function(i,item) {
                   if(i==0){
                        ht += '<li onmouseover="javascript:hoverCountryItem(this);" class="country_item_h"><a href=http://'+item.url+'><p>'+item.countryName+'<p><a></li>';
                   }else{
                        ht += '<li onmouseover="javascript:hoverCountryItem(this);"><a href=http://'+item.url+'><p>'+item.countryName+'<p><a></li>';
                   }
                });
                //$(".search_list").append('<li> </li>' );
                $(".search_list").html(ht);
             },
             error: function(){
                 alert('fail');
             }
         });
}
</script>


服務端:

/**
	 * 查詢國家匹配(lua專用)
	 * @return由於出現錯誤 c00ce56e 而導致此項操作無法完成。
	 * @throws Exception
	 */
	public String match_country_lua()throws Exception{
		PrintWriter out = null;
		String resultJson=null;
		//getResponse().setContentType("text/json;charset=utf-8");
        try {
		out = response.getWriter();
		
		PagerModel<LanguageStation> pm = languageStationRsClientImpl.pageForBbd(request.getParameter("l"), request.getParameter("q"));
		if(pm != null ){
			if(pm.getDatas() != null){
				resultJson= JSONObject.toJSONString(pm.getDatas());
			}
		}
		
		//boolean jsonP = false;
		String cb = request.getParameter("callback");
		response.setContentType("text/javascript");
		
		
		if(resultJson!=null)
		{
        out.write(cb+"("+resultJson+");");  
        out.flush();  
		}
		out.close(); 
    	} 
        catch (IOException e) 
        {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return NONE;
		
	}