繁体   English   中英

jQuery post成功返回空对象

[英]jquery post onsuccess returning null object

我在返回数据表时在json post success函数中获取空对象。 我已经用谷歌搜索了这个问题,但找不到它,需要您的帮助。 下面是我的代码。

脚本和样式:

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <style type="text/css">
    /* Panel Dropdown  */
     .clickable
    {
        cursor: pointer;
    }

    .panel-heading span
    {
        margin-top: -20px;
        font-size: 15px;
    }
</style>
<script type="text/javascript">
    $(document).on('click', '.panel-info span.clickable', function (e) {
        var $this = $(this);
        if (!$this.hasClass('panel-collapsed')) {
            $this.parents('.panel').find('.panel-body').slideUp();
            $this.addClass('panel-collapsed');
            $this.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
        } else {
            $this.parents('.panel').find('.panel-body').slideDown();
            $this.removeClass('panel-collapsed');
            $this.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
        }
    })
    $(function () {

        var max_fields = 10;
        var x = 0;
        var y;
        $('#add').click(function () {
            if (x < max_fields) {
                x++;
                if (x == 1) {
                    y = x;
                } else {
                    y = y + 3;
                }
                $("#addblock").before('<div class="col-md-14"><div class="panel panel-info">' +
                 '<a href="#" class="remove_field" title="Remove">Remove</a>' +
                 '<div class="panel-heading">' +
                 '<span class="menu-icon append-icon"></span><strong>Workout Type and Rates ' + x + '</strong>' +
                 '<span class="pull-right clickable"><i class="glyphicon glyphicon-chevron-up"></i></span>' +
                 '</div>' +
                 ' <div class="panel-body">' +
                 ' <table id="tblPanel' + x + '"><tr><td>Workout Type</td><td><input type="textbox" id=txtWorkoutType' + x + '></td></tr>' +
                 '<tr><td>Description</td><td><input type="textbox" id=txtDesc' + x + '></td></tr>' +
                 '<tr><td>Month</td><td><input type="textbox" id=txtMonth' + y + '></td><td><input type="textbox" id=txtMonth' + (y + 1) + '></td><td><input type="textbox" id=txtMonth' + (y + 2) + '></td><td><input type="textbox" id=txtMonth' + (y + 3) + '></td><td><input type="textbox" id=txtMonth' + (y + 4) + '></td></tr>' +
                 '<tr><td>Rate</td><td><input type="textbox" id=txtRate' + y + '></td><td><input type="textbox" id=txtRate' + (y + 1) + '></td><td><input type="textbox" id=txtRate' + (y + 2) + '></td><td><input type="textbox" id=txtRate' + (y + 3) + '></td><td><input type="textbox" id=txtRate' + (y + 4) + '></td></tr>' +
                 '<tr><td>Discount</td><td><input type="textbox" id=txtDiscount' + y + '></td><td><input type="textbox" id=txtDiscount' + (y + 1) + '></td><td><input type="textbox" id=txtDiscount' + (y + 2) + '></td><td><input type="textbox" id=txtDiscount' + (y + 3) + '></td><td><input type="textbox" id=txtDiscount' + (y + 4) + '></td></tr>' +
                 '</table>' +
                 '</div></div></div>');

                $("#hdnPanelinputCount").val(x);

            } else {
                alert("Only 10 entries are allowed");
            }

        });
        $(document).on('click', '.remove_field', function (e) {
            e.preventDefault();
            $(this).parent('div').remove();
            x--;
        });
    });

</script>

身体:

<div class="container">
        <div class="row">
          <div class="panel panel-success" id="addblock">
                <div class="form-group col-md-3 col-sm-3">
                    <input type='button' class="btn btn-primary" value="Add Workout Types" id="add" />
                </div>
            </div>


        </div>
        <input type='button' class="btn btn-primary" value="Submit" id="btnSubmit" />
    </div>
    <div>
        <table id="tbl">
            <tr>
                <th>Workout Type</th>
                <th>Month</th>
                <th>Rate</th>
                <th>Discount</th>
            </tr>
        </table>
    </div>
    <input id="hdnPanelinputCount" hidden="hidden" />

脚本:

     $("#btnSubmit").on('click', function () {
         var rowcount = $("#hdnPanelinputCount").val();
         var m = 0;
         var n;
         if (m < rowcount) {
             $("table[id^='tblPanel']").each(function () {
                 m++;
                 if (m == 1) {
                     n = m;
                 } else {
                     n = n + 3;
                 }
                 var WorkoutType = $("#txtWorkoutType" + m).val();
                 var Month1 = $("#txtMonth" + n).val();
                 var Month2 = $("#txtMonth" + (n + 1)).val();
                 var Month3 = $("#txtMonth" + (n + 2)).val();
                 var Rate1 = $("#txtRate" + n).val();
                 var Rate2 = $("#txtRate" + (n + 1)).val();
                 var Rate3 = $("#txtRate" + (n + 2)).val();
                 var Discount1 = $("#txtDiscount" + n).val();
                 var Discount2 = $("#txtDiscount" + (n + 1)).val();
                 var Discount3 = $("#txtDiscount" + (n + 2)).val();
                 /* Validations */
                 if (WorkoutType === "") {
                     alert("Please enter Workout type");
                     $("#txtWorkoutType" + rowcount).focus();
                     return false;
                 }
                 if (Month1 === "") {
                     alert("First Month cannot be blank");
                     $("#txtMonth" + rowcount).focus();
                     return false;
                 }
                 if (Month1 != "" || Month2 != "" || Month3 != "") {
                     if (Rate1 === "") {
                         alert("First Month Rate cannot be blank");
                         $("#txtRate" + rowcount).focus();
                         return false;
                     }
                     if (Rate2 === "") {
                         alert("Please put rate corresponding of month");
                         $("#txtRate" + rowcount).focus();
                         return false;
                     }
                     if (Rate3 === "") {
                         alert("Please put rate corresponding of month");
                         $("#txtRate" + rowcount).focus();
                         return false;
                     }
                     //if (Rate1 != "" || Rate2 != "" || Rate3 != "")
                     //{
                     //    if (Discount1 === "" || Discount2 === "" || Discount3 === "") {
                     //        alert("Please put discount corresponding of rate");
                     //        return false;
                     //    }
                     //}
                 }

                 var strtable = '<tr><td>' + WorkoutType + '</td><td>' + Month1 + '</td><td>' + Rate1 + '</td><td>' + Discount1 + '</td></tr>' +
                   '<tr><td>' + WorkoutType + '</td><td>' + Month2 + '</td><td>' + Rate2 + '</td><td>' + Discount2 + '</td></tr>' +
                   '<tr><td>' + WorkoutType + '</td><td>' + Month3 + '</td><td>' + Rate3 + '</td><td>' + Discount3 + '</td></tr>';

                 $("#tbl").append(strtable);

             });

         }
         var HTMLtbl =
                       {
                           getData: function (table) {
                               var data = [];
                               table.find('tr').not(':first').each(function (rowIndex, r) {
                                   var cols = [];
                                   $(this).find('td').each(function (colIndex, c) {

                                       if ($(this).children(':text').length > 0)
                                           cols.push($(this).children('input').val().trim());
                                       else
                                           cols.push($(this).text().trim());
                                   });
                                   data.push(cols);
                               });
                               return data;
                           }
                       }

         var data = HTMLtbl.getData($('#tbl'));
         var parameters = {};
         parameters.array = data;
         alert(parameters);
         var request = $.ajax({
             async: true,
             cache: false,
             dataType: "json",
             type: "POST",
             contentType: "application/json; charset=utf-8",
             url: "FitnessStudioAdmin.aspx/SaveData",
             data: JSON.stringify(parameters),
             success: function (data, status, jqXHR) {
                 var objdata = $.parseJSON(data.d);
                 alert(objdata);
             },
             error: function (jqXHR, status, err) {
                 alert("Local error callback." + err);
         }  
         });
     });
 </script>

CS页面:

  [WebMethod]
public static string SaveData(string[][] array)
{
    DataTable dt = new DataTable();
     dt = new DataTable();
        dt.Columns.Add("WorkoutType");
        dt.Columns.Add("Description");
        dt.Columns.Add("Month");
        dt.Columns.Add("Rate");
        dt.Columns.Add("Discount");
        dt.Columns.Add("Results");
        foreach (var arr in array)
        {
            DataRow dr = dt.NewRow();
            dr["WorkoutType"] = arr[0];
            dr["Description"] = arr[0];
            dr["Month"] = arr[1];
            dr["Rate"] = arr[2];
            dr["Discount"] = arr[3];
            dr["Results"] = "";
            dt.Rows.Add(dr);
        }

        String result = null;
        DataSet ds = new DataSet();
        ds.Tables.Add(dt);
        result = DataSetToJSON(ds);
        return result;
}
public static string DataSetToJSON(DataSet ds)
{

    Dictionary<string, object> dict = new Dictionary<string, object>();
    foreach (DataTable dt in ds.Tables)
    {
        object[] arr = new object[dt.Rows.Count + 1];
        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            arr[i] = dt.Rows[i].ItemArray;
        }
        dict.Add(dt.TableName, arr);
    }

    JavaScriptSerializer json = new JavaScriptSerializer();
    return json.Serialize(dict);
}

我还需要你们的建议,我上面的代码是在动态面板中生成动态面板和输入控件,现在我需要复选框列表,该列表将来自数据库并填充每个面板中的数据。 我该怎么办呢?

您实际上不应该使用JavaScript序列化器,Microsoft建议您使用Newtonsoft Json.Net

应该使用Json.NET进行序列化和反序列化。 为启用AJAX的应用程序提供序列化和反序列化功能。

他们的方法是:

return JsonConvert.SerializeObject<Example>(example);

同样,您的方法签名应该是:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Example> GetExampleDataAsJson()
{
     // Return normal object, this will return as Json for you in the decorator.
}

另一个选择是HttpHandler文件。

public void ProcessRequest(HttpContext context)
{
     var content = JsonConvert.SerializeObject<Example>(example);
     context.Response.Write(content);
     context.Response.End();
} 

您有各种各样的方法,还请记住,如果返回json,则不需要Json.Parse(...)因为它已经作为有效的Json对象返回了。

另外,您的代码中的主要问题。 您应该序列化并通过HttpContext流推送该请求。 如果您利用它,则类似于处理程序,它应将有效值通过传递给Ajax。 另外,您可以利用Fiddler验证往返的请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM