【问题标题】:create jquery array for ajax post为ajax post创建jquery数组
【发布时间】:2015-06-16 12:20:22
【问题描述】:

如何将drp.getDateRange 的输出转换为数组,以便通过 AJAX 发布?

我已更新此代码以表示下面给出的建议

<script>
    var drp;
    var myArray = [];
    function makedatepicker() {
        drp = $("#myDate").datepicker({});
    }
    function getRange() {
        var data = $("#myOutput").serialize();
        console.log("This is the serialized element");
        console.dir(data);

        $.ajax({
          url: "myurl.com",
          type: 'post',
          data: data,
          success: function(response) {
               console.log("This is the response from your ajax script");
               console.dir(response);
          }
        });
    }
    $(document).ready(function () {
        makedatepicker();
    });
</script>

【问题讨论】:

  • 只需阅读一些文档,drp.getDateRange() 实际上会返回一个数组。如何在警报中显示它是否正常工作?
  • 您可以使用 chrome 开发工具调试数组,也可以通过它进行迭代:for( var key in array ) console.log(key + ': ' + array[key]);。它比警报更有效。

标签: javascript jquery ajax datepicker


【解决方案1】:

更新

关于 JSON 的说明。默认编码将是 url 格式编码。如果您希望请求以 JSON 格式发送数据,则需要添加..

content-type: "application/json; charset=utf-8", 

如果你返回 JSON,你应该添加 ...

 datatype : "json",

不确定您在后端使用哪种脚本语言,但如果是 PHP,您可以像这样发送回数组数据

echo json_encode($myArray);

我会将 JSON 内容添加到下面的示例代码中。

结束更新


如果您使用.serialize() 将其作为 ajax 数据发送,它将显示在您的帖子或获取数组中。

如果您使用的是数组,您可能需要使用.serializeArray()

您可以在开发者工具中查看对象或数组(Chrome 或 FF 中的 F12),使用 console.dir(someObject);

var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);

$.ajax({
  url: "myurl.com",
  type: 'post',
  datatype : "json",
  contentType: "application/json; charset=utf-8",
  data : JSON.stringify(data),
  beforeSend : function (){
            console.log("Before Send: Data looks like..");
            console.dir(data);
  },
  success: function(response) {
       console.log("This is the response from your ajax script");
       console.dir(response);
       console.log("parsing JSON ...");
       console.dir($.parseJSON(response));
  }
});

Chrome 开发者工具控制台,在这里您可以看到任何您的 console.log 或 console.dir

您可以通过单击“网络”选项卡来检查正在发送的 JSON。然后单击 ajax 脚本的名称,它将显示正在发送的数据。 (此外,单击“响应”选项卡将显示您的脚本发送回的内容。)

在下面的示例中,我使用上面的代码发送了一个 ajax 请求,它表明数据确实是一个 JSON 对象。

【讨论】:

  • 我已经尝试了您的建议(已编辑),但我在控制台中遇到错误。
  • Uncaught ReferenceError: conosole is not definedCalendarUpdate.cshtml:273 getRangeCalendarUpdate.cshtml:133 onclick
  • 我认为 conosole 没有定义,因为你想指的是 console。答案只是有点错误。)
  • @Gavin5511 抱歉,这只是一个错字。它显然应该是“控制台”而不是“控制台”
  • 感谢 NotoriousPet,我也错过了那个错字。我已经纠正了它,但我还没有看到任何使用提琴手发布到我的页面的 JSON?上面的代码是否正确(我已经编辑了我的原始帖子)
猜你喜欢
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 2012-05-30
相关资源
最近更新 更多