jsonp实现跨域访问
要实现JSONP跨域访问,首先就要了解什么是跨域?然后JSONP与JSON的关系? 1、什么是跨域? 跨域简单的说就是一个域名下的程序和另一个域名下的程序做数据交互。比如说:现有一个http://www.zq.com和http://www.qt.com两个独立的网站,要实现从后一个网站向前一个网站中取数据。把做为数据来源的当作服务端,把去获取数据的当作客户端,实现面向服务的编程。 在动态网页当中,最重要的一项就是取数据。如果是在同一个项目中,将网站挂在同一个域名下,这种情况下无论是前台Ajax还是后台直接取数据都非常方便。但是如果像上面的两个网站一样,在不同的域名下,那么取数据就变得非常麻烦(现在有Web Servers和WCF实现面向服务的编程) 2、什么情况下用JSONP做跨域访问? 当要用Ajax从其它的项目中取数据时候。如果是在后台中从其它网站取数据,可用Web Servers或WCF等技术来实现。 3、JSONP和JSON的关系? JSON是一种基于文本的数据交互方式,而JSONP是基于JSON的使用方式。从使用上简单的讲就是:不跨域 用JSON实现A jax和后台数据交互; 跨域 用JSONP实现Ajax和其它域中程序做数据交互。 4、$.ajax实现JSONP <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PRequest.aspx.cs" Inherits="jsonP.PRequest" %> <!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> <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script src="Scripts/json2.js" type="text/javascript"></script> <script type="text/javascript"> function aa() { var person = {};//自定义数组 person.name = "aName"; person.age = 18; //console.log(JSON.stringify(person)); $.ajax({ url: "http://localhost:58878/jp.ashx",//另一个域中的程序 type: "get",dataType: "jsonp",//预期返回类型为JSONP data: { 'person': JSON.stringify(person) },jsonp: "callback",//在一个jsonp请求中重写回调函数的名字,可省 success: function (rt) { var result = JSON.parse(rt); //console.log(result); $("#lb").html(result.Name + "<br />" + result.Age); },error: function (e) { //console.log(e); } }); } </script> </head> <body> <input id="Button1" type="button" value="取值" onclick="aa()" /> <div id = "lb" style="width: 90px;height: 90px;background-color: red"></div> </body> </html> 通过分析不难发现其与JSON写法上的不同: 1、url上的细微差异,在JSONK中常是直接某个路径下的处理程序,而JSONP是写别的网站(域)下的处理代码程序路径。但要注意:JSON也能这样写 2、dataTypy现在处理的是JSONP而不是JSON 其它传参数据 ,接参数等和JSON并无二异 数据源部分
using System.Web; namespace PResponse { /// <summary> /// Summary description for jp /// </summary> public class jp : IHttpHandler { public class person { public string Name { get; set; } public int Age { get; set; } } public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string callback = context.Request["callback"];//callback不能少 string ca = context.Request["person"]; person b = Newtonsoft.Json.JsonConvert.DeserializeObject<person>(ca); string response = "{"Name":"" + b.Name + "","Age":"" + b.Age + ""}"; string re = Newtonsoft.Json.JsonConvert.SerializeObject(response); string call = callback + "(" + re + ")";//response和re相同,前面的callback不能少 context.Response.Write(call); } public bool IsReusable { get { return false; } } } } 这样就实现了跨域访问 5、说明 1)之所以在前台取数据要分JSON和JSONP,是因为JavaScript 的同源策略 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |