本文實例講述了json跨域調用python的方法。分享給大家供大家參考,具體如下:
客戶端:
<!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> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>jQuery-跨域請求</title> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> </head> <script type="text/javascript"> jQuery(document).ready(function(){ $.ajax({ type : "GET", url : "http://10.13.38.43:1234/?id=10&callback=?", dataType : "jsonp", jsonp: 'callback', success : function(json){ alert(json.account); //$('#msg_box').html(json); //return true; } }); }); </script> <body> <div id="msg_box"></div> </body> </html>
服務端
import weburls=('/','Index',)class Index: def GET(self): inputdata=web.input() mycallbackfun=inputdata.callback #return 'hello' +inputdata.id return mycallbackfun+'({"account":"XX","passed":"true","error":"null"})'app = web.application(urls, globals())if __name__=='__main__': app.run()
附:jquery跨域請求方法簡介
這里介紹jQuery跨域請求方法,并提供簡單的示例代碼供參考。
項目中關于ajax jsonp的使用,出現了問題:可以成功獲得請求結果,但沒有執行success方法,總算搞定了,記錄一下。
function TestAjax(){ $.ajax({ type : "get", async : false, url : "ajaxHandler.ashx", //實際上訪問時產生的地址為: ajax.ashx?callbackfun=jsonpCallback&id=10 data : {id : 10}, cache : false, //默認值true dataType : "jsonp", jsonp: "callbackfun",//傳遞給請求處理程序或頁面的,用以獲得jsonp回調函數名的參數名(默認為:callback) jsonpCallback:"jsonpCallback", //自定義的jsonp回調函數名稱,默認為jQuery自動生成的隨機函數名 //如果這里自定了jsonp的回調函數,則success函數則不起作用;否則success將起作用 success : function(json){ alert(json.message); }, error:function(){ alert("erroe"); } });}function jsonpCallback(data) //回調函數{ alert(data.message); //}public class ajaxHandler : IHttpHandler{ public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string callbackfun = context.Request["callbackfun"]; context.Response.Write(callbackfun + "({name:/"John/", message:/"hello John/"})"); context.Response.End(); } public bool IsReusable {get {return false;}}
ajax請求參數說明:
新聞熱點
疑難解答