本文实例讲述了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请求参数说明:
新闻热点
疑难解答