簡體   English   中英

從jQuery調用處理程序不起作用

[英]Calling handler from jQuery doesn't work

我需要從jQuery調用處理程序(ashx)文件以在運行時獲取一些數據。 我的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上搜索了很多,但是在我的代碼中找不到任何錯誤。

在更改了我傳遞json數據的方式(如@DRAKO的建議)並從ajax回發調用中刪除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...
        }
    });
});

我認為您將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");
            }

        });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM