AJAX跨域實現
阿新 • • 發佈:2017-05-11
res app empty index 如果 itl code get adt
原理:在同域中建立一個用於請求 別的域的代理程序,並將返回的內容發給客戶端,客戶端指向同域的這個代理程序
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 + "用戶以被註冊!請更換用戶名!"); } }
AJAX跨域實現