1. 程式人生 > >$.getJSON回撥函式不執行

$.getJSON回撥函式不執行

最近做的專案遇到一個跨域請求做驗證的問題,為了解決這個跨域問題,愁了老半天,最後發現jQuery提供的一個特別簡單的方法,就是用jQuery.getJSON(url, [data], [callback])

jQuery的Api提供一個列子:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data){
  $.each(data.items, function(i,item){
    $("<img/>").attr("src", item.media.m).appendTo("#images");
    if ( i == 3 ) return false;
  });
});

說明一下注意事項:

2、第二個引數一定要是json格式鍵/值對的格式。例:{ "email": "[email protected]"}

3、回撥函式,您請求的地址需要返回資料,返回的資料必須是嚴格的json格式的資料,還需要用 引數jsoncallback加小括號包裹jsoncallback(json格式的資料),否則就會出現回撥函式不會執行的問題。

下面有有兩個頁面參考:

a.jsp:

<html>
  <head>
    <title>TEST</title>
    <script type="text/javascript" src="./jquery-1.6.2.min.js"></script>

    <script type="text/javascript">
       jQuery(function(){
            $.getJSON("http://www.ma.com/ids/cn/

[email protected]&callback=?", function(data){
                 alert(data.resultMsg);  
            });

      });
    </script>
  </head>
  <body>
  </body>
</html>

b.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="/error.jsp" %>

<%
    response.setContentType("application/json");//這個一定要加
    String callback =    request.getParameter("callback");
     int status = 0;
      String remsg = "{\"resultMsg\":\""+status+"\"}";
%>
<%=callback+"("+remsg+")"%>

相關推薦

no