【问题标题】:Passing parameters to AJAX for binding DataTable is not working将参数传递给 AJAX 以绑定 DataTable 不起作用
【发布时间】:2021-06-22 13:27:19
【问题描述】:

我想为 pdf、excel、排序等使用 jQuery DataTable 插件来使用所有这些功能

我想从表中过滤记录,因为我将一些参数从客户端JSON>stringfy(My_Prametrs) 传递给WebMethod,并且方法过滤数据并以 JSON 格式返回客户端,但它无法与表绑定为什么会这样?

如果我使用无参数方法,它会按预期工作,能够绑定表

简单来说

无参数方法完美运行,但那些持有参数的方法不起作用,为什么?

AJAX

function LoadTableData() {
  var params = {
    //UserName: "@xc", UserID: "@xc", Status: "InActive"
    UserName: $('#txtUserName').val(),
    UserID: $('#txtUserID').val(),
    Status: $('input[name="Status"]:checked').val()
  };
  $.ajax({
    url: 'UserService.asmx/Get_Data',
    method: 'post',
    data: JSON.stringify(params),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data) {
      $('#example').dataTable({
        data: data /*JSON.parse(data)*/ ,
        columns: [{
          /*My columns */
        }],
        dom: 'Bfrtip',

        buttons: [
          'copy', 'csv', 'excel', 'pdf'
        ],
        "searching": true,
        "paging": true,
        "info": true,
        "language": {
          "emptyTable": "No data available"
        },
      })
    },
    error: function(err) { // Added this event to capture the failed requests.
      console.log(err.responseText);
    }
  });

服务器端网络方法

[WebMethod]
public void Get_Data(string UserName, string UserID, string Status)
{
  DataTable dt_MobileUserLogin = FAV_VS_BLL.Search_MobileUserLogin(UserName, UserID, Status);
    List<MobileUserMaster> list = new List<MobileUserMaster>();

    foreach (DataRow dr in dt_MobileUserLogin.Rows)
    {
        list.Add(new MobileUserMaster
        {
            USER_LOGIN = dr["USER_LOGIN"].ToString(),
            USER_NAME = dr["USER_NAME"].ToString(),
            Status = dr["status"].ToString(),
            PASSWORD = dr["PASSWORD"].ToString()
        });
    }
    JavaScriptSerializer jss = new JavaScriptSerializer();
    //return jss.Serialize(list);
    Context.Response.Write(jss.Serialize(list));

}

MobileUserMastr 类

public class MobileUserMaster
    {
        public string PASSWORD { get; set; }
        public string USER_LOGIN { get; set; }
        public string USER_NAME { get; set; }
        public string Status { get; set; }
    }

我没有得到有效的JSON

我得到像 JSON 一样的

[{
    "PASSWORD": "123",
    "USER_LOGIN": "@xc",
    "USER_NAME": "@xc",
    "Status": "Inactive"
}] {
    "d": null
}

我做错了什么?

请帮助我,因为我在这个问题上停留了一个星期

【问题讨论】:

  • 请改进语言 - 我听不懂你想说什么......
  • @helle 确定我会以正确的方式再次更新我的代码
  • @helle 你能帮帮我吗
  • 正如您发布的服务器端代码一样,它不会返回任何内容。你能更新那部分吗?
  • @pcalkins 我在控制台窗口上使用了Context.Response.Write(jss.Serialize(list));,我可以看到数据以 json 格式输入

标签: c# jquery asp.net ajax datatables


【解决方案1】:

尝试替换

var params = {
    UserName: $('#txtUserName').val(),
    UserID: $('#txtUserID').val(),
    Status: $('input[name="Status"]:checked').val()
  };
  $.ajax({
    url: 'UserService.asmx/Get_Data',
    method: 'post',
    data: JSON.stringify(params),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
 success: function(data) {

var userData = {
     UserName: $('#txtUserName').val(),
    UserID: $('#txtUserID').val(),
    Status: $('input[name="Status"]:checked').val()
  };

  $.ajax({
    url: '/UserService.asmx/Get_Data',
    method: 'POST',
    data: userData,
 success: function(data) {

然后试试这个序列化:

 var jss = new JavaScriptSerializer();
  var json= jss.Serialize(list);
 context.Response.ContentType = "text/json";
context.Response.Write(json);

【讨论】:

  • 我按照您的建议尝试了相同的方法,但我收到了类似{"Message":"Invalid JSON primitive: UserName.","StackTrace":" System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}的错误
  • 你可以试试 userData= { UserName: "xc", UserID: "xc", Status: "InActive"} 没有@
  • Ì 没有得到正确的 JSON 我的 json 数据中的数据终于附加了 {"d": null}
  • 如果我使用像 UserName: "@xc", UserID: "@xc", Status: "InActive" 这样的硬编码值,我会在控制台窗口上得到响应:[{"PASSWORD":"123","USER_LOGIN":"@xc","USER_NAME":"@xc","Status":"Inactive"}]{"d":null} 似乎 JSON 的格式不正确
  • 我不明白 {"d":null} 来自哪里?我没有看到这样的代码
【解决方案2】:

谢谢大家:

我只是把我的班级改成:

public class MobileUserMaster
    {
        public MobileUserMaster() { }
        public string PASSWORD { get; set; }
        public string USER_LOGIN { get; set; }
        public string USER_NAME { get; set; }
        public string Status { get; set; }
    }

因为我得到了

{
"d": null
}

所以我们必须在使用 Context.Response.Clear() 在服务器端给出响应之前从 ASP.NET Webservice 中清除默认响应 {d:null} 并设置 contentType

我使用下面的代码来序列化:

Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.AddHeader("content-length", stringJSON.Length.ToString());
Context.Response.Flush();
Context.Response.Write(stringJSON);
HttpContext.Current.ApplicationInstance.CompleteRequest();

它开始工作了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2023-03-19
    • 2020-04-06
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多