同一段邏輯代碼須要在多個網站中使用, 每一個網站都新建一個ashx真是扯蛋的做法, 因此想只請求一處的ashx, 這樣便於維護和修改, 那麼,ajax跨域問題就來了。 前端
廢話少說, 直接上代碼, 我如今作的是GET請求的。 POST請求同理。 web
首先整改ashx,加入支持跨域請求的代碼。ajax
context.Response.ContentType = "text/plain"; string active = context.Request.QueryString["active"]; string rs = "0"; if (active == "3") { string oid = TGM.BaseOpera.String.replacesql(context.Request.QueryString["oid"]); if (!string.IsNullOrEmpty(oid)) { tansar.BLL.order tbo = new tansar.BLL.order(); string flag = tbo.GetSID(oid); if (flag != "1000") rs = "ok"; } } #region 支持跨域請求 context.Response.ClearHeaders(); string origin = context.Request.Headers["Origin"]; context.Response.AppendHeader("Access-Control-Allow-Origin",string.IsNullOrEmpty(origin) ? "*" : origin); string requestHeaders = context.Request.Headers["Access-Control-Request-Headers"]; context.Response.AppendHeader("Access-Control-Allow-Headers",string.IsNullOrEmpty(requestHeaders) ? "*" : requestHeaders); context.Response.AppendHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); #endregion context.Response.Write(rs);
而後ajax中的js方法:sql
function getFlag(d) { $.ajax({ type: "get", async: false, url: "http://www.8kmm.com",
data: d,
dataType: "text",
success: function (data) {
if (data == "ok") {
location.href = "/user/orderdetail.aspx?oid=<%=Onumber %>"; }
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("請求數據異常:" + errorThrown);
}
});
}
作前端開發, 瀏覽器的開發者工具能幫大忙, 好比webkit內核的, ff的。 跨域