【问题标题】:How do I send an array in an .ajax post using jQuery?如何使用 jQuery 在 .ajax 帖子中发送数组?
【发布时间】:2011-01-25 02:04:24
【问题描述】:

我已经遍历了一个简单的收集数据并将其推送到一个数组中。然后我试图将该数组发送到页面方法(.aspx)。数组有一些东西不像我想的那样。这是我的代码:

//packaging table data for submit to server
            $("#saveToDB").click(function() {
                var dataForSubmit = new Array();
                //gather all data to array except the "delete" cell, .rowToDelete
                $('#QueueTable tbody td:not(.rowToDelete)').each(function() {
                    dataForSubmit.push($(this).html());

                });
                //test the array
                //alert(dataForSubmit);

                //send array to method
                $.ajax({
                    type: "POST",
                    url: "DailyReceipts.aspx/saveData",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: dataForSubmit,
                    success: function(msg) {
                        $.jGrowl('Your data has been successfully saved.', { header: 'Important' });
                        $('#result').append(msg.d)
                    },
                    error: function() {
                        $.jGrowl('An error has occured in saving the data.', { header: 'Important' });
                    }
                });
            });

【问题讨论】:

  • 你有什么错误吗?您的服务器端脚本如何?看来您正在使用 PageMethods。
  • 它达到了我的错误处理。服务器端看起来像这样: public void saveData(string[] theData)

标签: jquery ajax json post


【解决方案1】:

只需在 data 参数上附加它期望的任何参数,如下所示:

data: "paramName=" + dataForSubmit,

或者,或者:

data: { paramName : dataForSubmit },

【讨论】:

  • @Matt - 将其放入您的错误处理程序以查看错误是什么:error:function (xhr, opt, aError){ alert(xhr.status); alert(aError); }
  • @Matt - 这意味着服务器错误,在 asp.net 方面发生了一些问题,您可以连接调试器或记录以查看什么吗? FireBug 对此也非常有帮助:getfirebug.com
  • Firebug 说我的 JSON 无效?我没有我的 [Web Method] 静态,因此可以解释服务器端问题。对不起,伙计,我对这些东西不熟悉..
  • @Matt - 你修复了服务器端,还有问题吗?如果是这样,请更新,我们会看到问题所在。
【解决方案2】:

你应该使用这个函数:JSON.stringfy,所以:

//send array to method
                $.ajax({
                    type: "POST",
                    url: "DailyReceipts.aspx/saveData",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringfy(dataForSubmit),
                    success: function(msg) {
                        $.jGrowl('Your data has been successfully saved.', { header: 'Important' });
                        $('#result').append(msg.d)
                    },
                    error: function() {
                        $.jGrowl('An error has occured in saving the data.', { header: 'Important' });
                    }
                });

【讨论】:

    猜你喜欢
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2017-04-03
    • 1970-01-01
    • 2011-02-19
    • 2013-04-08
    相关资源
    最近更新 更多