【问题标题】:passing jquery data to WebMethod将 jquery 数据传递给 WebMethod
【发布时间】:2012-02-04 19:23:31
【问题描述】:

我知道我们已经有很多关于这个主题的帖子,但我就是不知道如何将数据传递给 WebMethod!我只需要将一个字符串数据传递给我的 WebMethod,但我需要使用列表数据类型吗?

.js

function buttonClicked () {
$.ajax({
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    url: "Chat.aspx/send",
    data: "{'text':'" + $("#writeBox").val() +  "'}",
    success: function () {
    },
    error: function () {
    }
});
}

.aspx(已更新完整代码)//我注释掉了导致错误的部分

[System.Web.Services.WebMethod]
void send (string text) {
    string id = HttpContext.Current.Request.Cookies["id"].ToString();
    string queryString = "INSERT INTO Log (ID, Text, Date) Values (" + id + ", " + text + ", GETDATE())";
    System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLExpress;Initial Catalog=ChatV1;Integrated Security=True");
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(queryString, con);
    using (con)
    {
       con.Open();
       //cmd.ExecuteNonQuery();
    }
}

【问题讨论】:

  • 你做得对,你有什么问题?!
  • 我在 chrome javascript 控制台上收到 500 Internet 服务器错误。

标签: jquery asp.net webmethod


【解决方案1】:
[System.Web.Services.WebMethod]
public static void send (string text) {
    string id = HttpContext.Current.Request.Cookies["id"].ToString();
    string queryString = "INSERT INTO Log (ID, Text, Date) Values (" + id + ", " + text + ", GETDATE())";
    System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLExpress;Initial Catalog=ChatV1;Integrated Security=True");
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(queryString, con);        
       con.Open();
       cmd.ExecuteNonQuery();
       con.Close();
}

【讨论】:

  • 我不能使用静态方法,因为我需要使用 Request.Cookies 集合来检索我的 cookie。我发现我不能使用静态方法的集合:(
  • 所以改变你调用ajax请求的策略。使用 PHP 样式调用 ajax 请求(我的意思是使用其他网页并通过您的 ajax 请求调用它,而不是 web 方法)
  • @SiYoungKim 您是否尝试过 HttpContext.Current.Request.Cookies 以静态方法访问 cookie 集合?
  • @AliForoughi 感谢 JQone,我可以将其设为静态,现在它似乎可以工作了!除非我在我的网络方法中包含 cmd.ExecuteNonQuery。
  • cmd.ExecuteNonQuery!!?需要更多细节,伙计
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 2017-03-02
相关资源
最近更新 更多