JS跨域總結
2024-05-06 14:21:21
供稿:網友
javascript跨域有兩種情況:
1、基于同一父域的子域之間,如:a.c.com和b.c.com
2、基于不同的父域之間,如:www.a.com和www.b.com
3、端口的不同,如:www.a.com:8080和www.a.com:8088
4、協議不同,如:http://www.a.com和https://www.a.com
對于情況3和4,需要通過后臺proxy來解決,具體方式如下:
a、在發起方的域下創建proxy程序
b、發起方的js調用本域下的proxy程序
c、proxy將請求發送給接收方并獲取相應數據
d、proxy將獲得的數據返回給發起方的js
發起方頁面代碼如下:
代碼如下:
<form id="form1" runat="server">
<div>
<input type="text" id="txtSrc" value="http://www.gzsums.edu.cn/webclass/html/html_design.html" style="width: 378px" />
<input id="btnProxy" type="button" value="通過Proxy獲取數據" onclick="GetDataFromProxy();" /><br />
<br />
<br />
</div>
<div id="divData"></div>
</form>
</body>
<script language="javascript" type="text/javascript">
function GetDataFromProxy() {
var src = document.getElementById('txtSrc').value;
var request = null;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function() {
var ready = request.readyState;
var data = null;
{
if (ready == 4) {
data = request.responseText;
document.getElementById('divData').innerHTML = data;
}
else {
document.getElementById('divData').text = "Loading";
}
}
}
var url = "Proxy.ashx?src=" + escape(src);
request.open("get",url,false);
request.send(null);
}
</script>
發起方Proxy代碼如下:
代碼如下:
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Net;
using System.Text;
namespace WebApplication1
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Proxy : IHttpHandler
{
const int BUFFER_SIZE = 8 * 1024;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string src = context.Request["src"];
WebRequest wr = WebRequest.Create(src);
WebResponse wres = wr.GetResponse();
Encoding resEncoding = System.Text.Encoding.GetEncoding("gb2312");
StreamReader sr = new StreamReader(wres.GetResponseStream(), resEncoding);
string html = sr.ReadToEnd();
sr.Close();
wres.Close();
context.Response.Write("<br/><br/><br/><br/>");
context.Response.Write(html);