您的位置:首页 > 理论基础 > 计算机网络

利用jsonp实现http 的跨域访问

2013-06-06 14:17 393 查看
弄了半天终于弄明白了。

目前我实现的是html的客户端页面 http访问 python的服务端。

服务端: (网上例子java servlet)

清单 7. 用 Java servlet 实现的 JSONP 服务

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String jsonData = getDataAsJson(req.getParameter("symbol"));
String output = req.getParameter("callback") + "(" + jsonData + ");";

resp.setContentType("text/javascript");

PrintWriter out = resp.getWriter();
out.println(output);
// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
}

http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/

http请求的服务端 只要返回的是上面红色高亮部分就行了

这个也是可以:

1     public class MyService : IHttpHandler
2     {
3         public void ProcessRequest(HttpContext context)
4         {
5             //获取回调函数名
6             string callback = context.Request.QueryString["callback"];
7             //json数据
8             string json = "{\"name\":\"chopper\",\"sex\":\"man\"}";
9
10             context.Response.ContentType = "application/json";
11             //输出:回调函数名(json数据)
12             context.Response.Write(callback + "(" + json + ")");
13         }
14
15         public bool IsReusable
16         {
17             get
18             {
19                 return false;
20             }
21         }
22     }

/article/5315908.html 

客户端:

html页面

$.getJSON("http://localhost:10085/show?appid=34567890&&callback=?", onDataReceived);

或者

$.getJSON("http://localhost:20002/MyService.ashx?callback=?",function(data){
alert(data.name + " is a a" + data.sex);
});




$.ajax({

93 url: 'http://localhost:10085/show?callback=?',

94 method: 'GET',

95 dataType: 'jsonp',

96 data: setQueryString(),

97 success: onDataReceived

98 });
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: