如何将json类型数据附加到新FormData

时间:2016-03-02 00:32:28

标签: javascript php jquery json

我有一个像这样的php文件

<form id="f-comment" class="form" method="post" action="submit_img_comment.php">
    <textarea name="comment"></textarea>
    <input type="submit" value="Publish" data-params='{"imageid":<?php echo $imageid; ?>}'>
</form>

我使用jQuery ajax

发送表单
$(document).on("submit", ".form", function(e) {
    e.preventDefault();

    // what form are you submitting?
    var form = $("#" + e.target.id);

    // parameters to send along with data
    var params = $(this).data("params");

    $.ajax({
        type: form.attr("method"),
        url: "include/" + form.attr("action"),
        data: new FormData(this),
        dataType: "json",
        contentType: false,
        processData: false,
        cache: false
    }).done(function(data) {
        alert(data['msg']);
    }).fail(function(data) {
        alert("Error: Ajax Failed.");
    }).always(function(data) {
        // always do the following, no matter if it fails or not
    })
});

到目前为止一切顺利。

唯一缺少的是如何将params添加到FormData。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

使用.append(),请参阅Using FormData Objects;在params$(input[type=submit], this)的声明处调整选择器,其中thisform.data()引用.data()input type="submit"元素< / p>

 $(document).on("submit", ".form", function(e) {
    e.preventDefault();
    var data = new FormData("form", this);
    var params = $("input[type=submit]", this).data("params");
    data.append("params", params);
    $.ajax({
        type: form.attr("method"),
        url: "include/" + form.attr("action"),
        data: data,
        dataType: "json",
        contentType: false,
        processData: false,
        cache: false
    }).done(function(data) {
        alert(data['msg']);
    }).fail(function(data) {
        alert("Error: Ajax Failed.");
    }).always(function(data) {
        // always do the following, no matter if it fails or not
    })
  })

答案 1 :(得分:0)

对象FormData是向对象添加新参数的方法append

例如:

var FD = new FormData('id-form');
FD.append('name','value');