如何在asp.net web应用程序的不同目录下从jQuery ajax引用http处理程序文件

我的应用程序的以下目录中有一个http处理程序文件

在此处输入图像描述

我在common.js文件中引用此处理程序,使用在aspx页面中StoresSummary.aspx jQuery ajax和common.js文件StoresSummary.aspxEmployeeProfile.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; }