原理:在同域中建立一个用于请求 别的域的代理程序,并将返回的内容发给客户端,客户端指向同域的这个代理程序
1. 客户端编写
// 其它部分都一样
//2.注册回调方法 callback
xmlhttp.onreadystatechange = callback;
//获取客户端内容
var userName = document.getElementById("UserName").value;
//进行编码解决 中文乱码
userName = encodeURI(encodeURI(userName));
// 进行跨域AJAX请求操作
var url = "http://192.168.3.53/AjaxRequst.ashx";
if (url.indexOf("http://") == 0) {
//url = "http://192.168.3.53/AjaxRequst.ashx?name=123"
//如果URL请求是上面类型,组合的URL将有两个?号,将?号转换成&
url.replace("?", "&");
//Proxy.ashx是同域的 代理服务程序,用于访问 跨域的 AJAX
url = "Proxy.ashx?url=" + url;
}
//Post 请求方式
//3.设置和服务端交互的相应参数
xmlhttp.open("Post", url, true);
//Post方式需要增加的代码
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//4.设置向服务器发送数据,启动和服务端的交互
xmlhttp.send("name="+userName);
2.代理服务程序的编写 Proxy.ashx
//这里用的是 Get 请求,Post传值麻烦
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string name = context.Request["name"].ToString();
string url = context.Request["url"].ToString()+"?name="+name;
string result = string.Empty;
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
// 默认用 Get 请求,以下为Post请求但还未传值
//httpReq.Method = "Post";
//httpReq.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse HttpWResp = (HttpWebResponse)httpReq.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(HttpWResp.GetResponseStream(), System.Text.Encoding.UTF8);
result = reader.ReadToEnd();
context.Response.Write(result);
context.Response.End();
}
3.跨域的服务程序 AjaxRequest.ashx
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
if (context.Request["name"] == null)
{
context.Response.Write("用户名不能为空!");
return;
}
string name = context.Request["name"].ToString();
if (name != "xgao")
{
context.Response.Write(name+"用户可以注册!");
}
else
{
context.Response.Write(name + "用户以被注册!请更换用户名!");
}
}

浙公网安备 33010602011771号