0

実行時にデータを取得するには、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) ファイルを呼び出すことができます。したがって、パスの問題ではありません。

私はこのハンドラー ファイルの概念に不慣れです。私はたくさんグーグルで検索しましたが、コードに問題は見つかりませんでした。

4

2 に答える 2

2

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...
        }
    });
});
于 2012-04-26T12:37:26.457 に答える
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");
            }

        });
    });
于 2012-04-26T04:47:41.790 に答える