关于跨域大概可以分iframe的跨域,和纯粹的跨全域请求。
原文地址:https://mp.weixin.qq.com/s?__biz=MjM5NzA1MTcyMA==&mid=403031230&idx=2&sn=7908ded106360a9c68cb98b02195487c&scene=1&srcid=0301ke14YYuBZlbfv3876gWq&key=710a5d99946419d9910a8cd82aae16da26b02eee7508ef038bb2e779aff191afcaad746e8b90a7055752d1640c1a504c&ascene=1&uin=MTEzMTQ4MzE4MA%3D%3D&devicetype=Windows-QQBrowser&version=61030003&pass_ticket=tcAw0djiR2lSXVb7OH%2Fqf927%2BU%2FXmuV3cfxKhAZK91CdjqeNjZuzTXdntokClCYS
关于跨域的可以去看园子里的这几篇文章:
-
JavaScript跨域总结与解决办法(http://www.cnblogs.com/rainman/archive/2011/02/20/1959325.html)
-
跨域-知识(http://www.cnblogs.com/scottckt/archive/2011/11/12/2246531.html)
-
跨域资源共享的10种方式(http://www.cnblogs.com/cat3/archive/2011/06/15/2081559.html)
其实正统的跨全域的解决方法大致也就,JSONP,Access Control和服务器代理这么三种
实例:
前端JavaScript跨域调用:
第一种方法
<script type="text/javascript" src="YourURL?jsonCallback=onLoaded"></script>
第二种方法
function onLoaded(jsonData) {
//处理显示jsonData内容
}
var url = "YourURL?jsonCallback=onLoaded&sth=" + sth;
$.ajax({
type: "get",
url: url,
dataType: "jsonp",
//ajax 传参的两种方法:data: "orderId=" + orderId + "&commant=" + commant;
// data: {"orderId":orderId,"commant":commant},
callback: "onLoaded"
});
后台WebServer跨域调用api接口:
public static string GetUrlResult(string URL)
{
//C#利用System.Uri转URL为绝对地址
Uri uri = new Uri(URL);
//通过使用接受数据的资源(例如脚本或 ASP .NET 页)的 URI 调用 Create,创建一个 WebRequest 实例。
//详细:https://msdn.microsoft.com/zh-cn/library/debx8sh9(VS.80).aspx
WebRequest webReq = WebRequest.Create(uri);
try
{
// 发送HttpWebRequest等待响应
// C#-using用法详解: http://blog.youkuaiyun.com/wanderocn/article/details/6659811/
using (HttpWebResponse webRes = (HttpWebResponse)webReq.GetResponse())
{
//获取与该响应相关的流
using (Stream respStream = webRes.GetResponseStream())
{
//读取流
using (StreamReader objReader = new StreamReader(respStream, System.Text.Encoding.UTF8))
{
//ReadToEnd适用于小文件的读取,一次性的返回整个文件
string strRes = objReader.ReadToEnd();
return strRes;
}
}
}
}
catch (WebException)
{
return "";
}
}
public static IList<Ext> Example()
{
string URL="http://www.baidu.com/xxx/xxx?id=1&password=111";
string result=APIInterfaceUtil.GetUrlResult(URL);
System.Web.Script.Serialization.JavaScriptSerializer json=new System.Web.Script.Serialization.JavaScriptSerializer();
Ext o = json.Deserialize<Ext>(result);
//反序列化Deserialize、 序列化Serialize
//eg. User user = json.Deserialize<User>(jsonString)
// string jsonString = json.Serialize(user)
Ext m = new Ext();
if (o != null && o.Result == true)
{
IList<Ext> list = o.list;
return list;
}
return null;
}