【问题标题】:JQuery Ajax Post to C#JQuery Ajax 发布到 C#
【发布时间】:2023-03-25 17:10:02
【问题描述】:

我正在尝试在 C# 上检索 JSON 对象,这是我的 JavasSciprt 帖子,但我无法在代码隐藏中处理它,谢谢!

$.ajax({
    type: "POST",
    url: "facebook/addfriends.aspx",
    data: { "data": response.data },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        location = '/facebook/login?URL=' + ReturnURL + '&UID=' + response.authResponse.userID + '&TK=' + response.authResponse.accessToken + '';
    }
});

我尝试检索如下数据:

Request.Form["data"]
Request["data"]

【问题讨论】:

    标签: c# jquery asp.net ajax json


    【解决方案1】:

    这是来自Encosia.com 的示例(我添加了一个表单参数)。你不需要访问Page.Form - 你可以使用方法参数来代替。

    代码隐藏

    public partial class _Default : Page 
    {
      [WebMethod]
      public static string GetDate(string someParameter)
      {
        return DateTime.Now.ToString();
      }
    }
    

    Javascript

    $(document).ready(function() {
      // Add the page method call as an onclick handler for the div.
      $("#Result").click(function() {
        $.ajax({
          type: "POST",
          url: "Default.aspx/GetDate",
          data: {someParameter: "some value"},
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(msg) {
            // Replace the div's content with the page method's return.
            $("#Result").text(msg.d);
          }
        });
      });
    });
    

    【讨论】:

    • 谢谢,但我不想将数据从 C# 获取到 Javascipt 我正在尝试将数据从 JavaScript 发布到 C#
    • 是的,但它不包含代码隐藏上的数据持有者,我认为 WebMethod 关键字可以完成这项工作?
    • 你看到someParameter方法参数了吗?这是你的帖子数据。
    • 谢谢这工作,但我得到了 response.data is not a JSon object 之类的错误
    • 这不是很丰富。一堆没有解释的代码。
    【解决方案2】:

    我就是这样做的,它对我有用:

    $.ajax({
        type: "POST",
        url: "facebook/addfriends.aspx",
        data: "data=" + response.data + "&data1=anyothervaluelikethis",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        success: function (msg) {
            location = '/facebook/login?URL=' + ReturnURL + '&UID=' + response.authResponse.userID + '&TK=' + response.authResponse.accessToken + '';
        }
    });
    

    这两行修改

     data: "data=" + response.data + "&data1=anyothervaluelikethis",
     contentType: "application/x-www-form-urlencoded",
    

    【讨论】:

      【解决方案3】:

      代码隐藏 C# 方法签名应类似于:

      [WebInvoke(UriTemplate = "MyMethod", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
      public Object MyMethod(Object data){
       // your code
      }
      

      其中 Object 可以是任何可序列化的类

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-07
        • 2011-12-06
        • 1970-01-01
        • 1970-01-01
        • 2016-07-23
        • 2011-03-09
        • 2013-08-14
        相关资源
        最近更新 更多