如何在asp.net web应用程序的不同目录下从jQuery ajax引用http处理程序文件
我的应用程序的以下目录中有一个http处理程序文件
我在common.js
文件中引用此处理程序,使用在aspx页面中StoresSummary.aspx
jQuery ajax和common.js
文件StoresSummary.aspx
和EmployeeProfile.aspx
从EmployeeProfile.aspx
我能够调用处理程序并获取输出,但是从StoresSummary.aspx
jquery ajax调用失败。
我知道失败的原因,因为CommonHandler.ashx
位置层次结构导致CommonHandler.ashx
文件的路径无法正确StoresSummary.aspx
。
这是我发布的示例代码,我需要从Jquery ajax调用的http处理程序文件和aspx页面可能存在于同一Web应用程序的不同目录中。
我需要如何在ajax jQuery调用中给出CommonHandler.ashx
路径,这样我的aspx页面的任何位置层次都可以调用它。
这是我的代码
common.js
function GetMessage(key) { var message = ''; $.ajax({ type: 'POST', url: '../../Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/ contentType: 'application/json; charset=utf-8', dataType: 'json', data: { 'MessageKey': key }, success: onSucess, error: OnFailed, async: false }); function onSucess(res) { message = res; } function OnFailed(res) { alert('failed'); } return message; }
StoresSummary.aspx
function CallMethod() { var msg = GetMessage('001'); alert(msg); return false; }
EmployeeProfile.aspx
function CallMethod() { var msg = GetMessage('001'); alert(msg); return false; }
CommonHandler.ashx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; namespace DemoWebApp.Common.Handlers { /// /// Summary description for CommonHandler /// public class CommonHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(GetData(context.Request["MessageKey"])); context.Response.ContentType = "text/html"; context.Response.Write(result); } private string GetData(string Id) { return DateTime.Now.ToString(); //just to demostrate } public bool IsReusable { get { return false; } } } }
您可以从root( /Common/Handlers/CommonHandler.ashx )开始路径,而不是相对路径( ../../Common/Handlers/CommonHandler.ashx )。 所以它适用于任何页面:
function GetMessage(key) { var message = ''; $.ajax({ type: 'POST', url: '/Common/Handlers/CommonHandler.ashx', /*Working for EmoloyeeProfile.aspx but not for StoresSummary.aspx*/ contentType: 'application/json; charset=utf-8', dataType: 'json', data: { 'MessageKey': key }, success: onSucess, error: OnFailed, async: false }); function onSucess(res) { message = res; } function OnFailed(res) { alert('failed'); } return message; }