-1

.net プロジェクトで Ajax を使用しています (MVC.net ではありません)。JScript 関数から .aspx.cs の関数を呼び出したいです。

これは私の JScript コードです:

    $("a#showQuickSearch").click(function () {
        if ($("#quick_search_controls").is(":hidden")) {
            $.ajax({
                type: "POST",
                url: "Default.aspx/SetInfo",
                data: "{showQuickSearch}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
               success: function(response) {
                     alert(response.d);
               }

            });
            $("#quick_search_controls").slideDown("slow");
            $("#search_controls").hide();
            $("#search").hide();
        } else {
            $("#quick_search_controls").hide();
        }

    });

そして、これは私の .aspx.cs 関数です:

   [WebMethod]
    public string SetInfo(string strChangeSession)
    {
        Label1.Text = strChangeSession;
        return "This is a test";
    }

問題は、.aspx.cs 関数が呼び出されておらず、label.text が更新されていないことです。

4

3 に答える 3

1

data: "{showQuickSearch}"は有効な JSON ではありません。

有効な JSON は次のようになります。

data: JSON.stringify({ strChangeSession: 'showQuickSearch' })

また、PageMethod は静的である必要があります。

[WebMethod]
public static string SetInfo(string strChangeSession)
{
    return "This is a test";
}

これは明らかに、ラベルなどのページ要素にアクセスできないことを意味します。PageMethod の結果を使用してラベルなどを更新できるようになったのは、成功のコールバック内です。

于 2012-07-09T22:04:05.390 に答える
1

関数を静的にしてみてください。

[WebMethod]
    public static string SetInfo(string strChangeSession)
    {
        //Label1.Text = strChangeSession; this wont work
        return "This is a test";
    }
于 2012-07-09T22:03:39.080 に答える
0
 $.ajax({
            type: "POST",
            url: "Default.aspx/SetInfo",
            data: "{'strChangeSession':'showQuickSearch'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
                 alert(response.d);
           },
          error: function (xhr, status, error) {

                var msg = JSON.parse(xhr.responseText);
                alert(msg.Message);
            }
        });

そしてあなたのバックエンドコード:

 [WebMethod]
 public static string SetInfo(string strChangeSession)
 {
   return "Response ";
 }
于 2012-07-09T22:29:17.737 に答える