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!

    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算