JQuery Ajax 发布到 C#

Posted

技术标签:

【中文标题】JQuery Ajax 发布到 C#【英文标题】:JQuery Ajax Post to C# 【发布时间】:2012-05-26 02:05:57 【问题描述】:

我正在尝试在 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"]

【问题讨论】:

【参考方案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 可以是任何可序列化的类

【讨论】:

以上是关于JQuery Ajax 发布到 C#的主要内容,如果未能解决你的问题,请参考以下文章

Python 操作Redis

python爬虫入门----- 阿里巴巴供应商爬虫

Python词典设置默认值小技巧

《python学习手册(第4版)》pdf

Django settings.py 的media路径设置

Python中的赋值,浅拷贝和深拷贝的区别