2012-04-26 73 views
0

我需要從jQuery調用處理程序(ashx)文件以在運行時獲取一些數據。 我jQuery的功能是這樣的:從jQuery調用處理程序不起作用

  var pID = 3; 
     var tID = 6; 

     $("#Button1").click(function() { 
      var urlToHandler = "Controller/TestHandler.ashx"; 
      $.ajax({ 
       type: "POST", 
       url: urlToHandler, 
       data: "{'pID':'" + pID + "', 'tID':'" + tID + "'}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function(msg) { 
        alert(msg); 
       } 
      }); 
     }); 

我的處理代碼:

<%@ WebHandler Language="C#" Class="TestHandler" %> 

using System; 
using System.Web; 

public class TestHandler : IHttpHandler 
{  
    public void ProcessRequest (HttpContext context) 
    { 
     String pID = context.Request.Params["pID"]; 
     String tID = context.Request.Params["tID"]; 
     context.Response.ContentType = "text/plain"; 
     context.Response.Write(pID + " " + tID); 
    } 

    public bool IsReusable 
    { 
     get { 
      return false; 
     } 
    } 
} 

的問題是執行代碼沒有達到的處理程序代碼。 我可以從處理程序文件所在的相同目錄中的相同jQuery函數調用其他Web窗體(aspx)文件。所以這不是任何路徑問題。

我是這個處理程序文件概念的新手。我GOOGLE了很多,但在我的代碼中找不到任何錯誤。

+0

小提琴手說什麼? (或螢火蟲?) – aquinas 2012-04-26 04:39:27

+0

它沒有顯示任何錯誤。 – 2012-04-26 04:43:22

+0

那麼,它會返回200,成功嗎? – aquinas 2012-04-26 04:45:49

回答

1

我認爲你傳遞json數據到處理程序的方式是不正確的。

還要確保處理程序的路徑是正確的,並在處理程序中向控制檯寫入一行以檢查它是否被調用。試試這個代碼出

$("#Button1").click(function(){ 

     $.ajax({ 
      type: "POST", 
      url: "/Controller/TestHandler.ashx", 
      data: {pID:pID, tID:tID}, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function(msg) { 
       alert(msg); 
      }, 
      error: function(){ 
       alert("Error"); 
      } 

     }); 
    }); 
+0

路徑是正確的,我可以從同一目錄調用其他Web窗體(aspx)文件。 @DRAKO我正在嘗試使用您建議的json數據更正。 – 2012-04-26 04:52:48

2

它改變我經過JSON數據(由@DRAKO的建議)的方式,並從阿賈克斯後回電話取出後的contentType工作。還糾正了路徑。

$("#Button1").click(function() { 
    var urlToHandler = "TestHandler.ashx"; 
    $.ajax({ 
     type: "POST", 
     url: urlToHandler, 
     data: { pID: pID, tID: tID }, 
     dataType: "json", 
     success: function(msg) { 
      //do something with the msg here... 
     } 
    }); 
}); 
+0

也適用於我 – 2012-08-24 08:25:32

相關問題