duankang5882 2016-06-29 03:41
浏览 77

如何让jQuery AJAX将.map函数var值作为JSON字符串发布

In example of option A below, the PHP script post result stated undefined when echo the post data. But at the same time the console.log displays: [Object { set_capture="resize", set_unknown="unknown"}]. I would like to know What is wrong with the .map function or the ajax code in option A ? For option B, it works well after removing the .map function. What am I missing ?

HTML Form:

<form action="myphp.php" method="post" name="form-foo">
    <input type="radio" id="r1" class="set-img" name="set_capture" value="resize" />
    <input type="radio" id="r2" class="set-img" name="set_capture" value="original" />
    <input type="checkbox" id="r3" class="set-img" name="set_unknown" value="unknown" />
    <input type="submit" id="submit" name="submit" value="Save" />
</form>

Option A:

$(function() {
  $("#submit").on("click", function() {
    var radioValues = $('#form-foo').map(function() {
      return {
        set_capture: $('input[name="set_capture"]:checked').val(),
        set_unknown: $('input[name="set_unknown"]:checked').val()
      };
    }).get();
    console.log(radioValues);
    //var formData = JSON.stringify(radioValues);
    var formData = radioValues;
    var formURL = $("#form-foo").attr("action");
    console.log(formData);
    $.ajax({
      url: formURL,
      type: "POST",
      data: formData,
      cache: false,
      dataType: "json"
    }).done(function(data) {
      // more codes
    }, "json");
    return false;
  });
});

Option B:

$(function() {
  $("#submit").on("click", function() {
    var capture = $('input[name="set_capture"]:checked').val();
    var unknown = $('input[name="set_unknown"]:checked').val();
    var formData = {
      set_capture: capture,
      set_unknown: unknown
    };
    var formURL = $("#form-foo").attr("action");
    console.log(formData);
    $.ajax({
      url: formURL,
      type: "POST",
      data: formData,
      cache: false,
      dataType: "json"
    }).done(function(data) {
      // more codes
    }, "json");
    return false;
  });
});
  • 写回答

2条回答 默认 最新

  • dtll2016 2016-06-29 04:54
    关注

    Ajax data must is array. EX:{"capture":123, "unknow":456}.

    With Option A: formData is [Object] not array, so it not working.

    With my knowledge, sorry if this wrong!

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能