2017-07-26 56 views
1

我相信我在某个地方犯了一个非常基本的错误。通过Json传输表单数据

我有一个表单我想传输到一个PHP页面。我也想发送一个带有这些信息的参数,所以我创建了一个基本的2D数组: $ fd ['api'] - >将参数作为字符串包含在内 $ fd ['body'] - >包含表格数据

我很努力地将这个数组“$ fd”作为json字符串传递,并且相信我在某处不正确地使用javascript语法,因为我不经常使用Javascript。

任何帮助,将不胜感激。

function admin_statistics_form_send(){ 
    var fd = [] 
    fd['api'] = "refresh_all" 
    fd['body'] = new FormData(document.getElementById("admin_statistics_form")) 
    var jsonstring = fd 
    console.log(jsonstring) 
    $.ajax({ 
    async: true, 
    beforeSend: function(){ 
    }, 
    url: "admin_statistics_api.php", 
    type: "POST", 
    data: jsonstring, 
    dataType: "json", 
    processData: false, // tell jQuery not to process the data 
    contentType: false, // tell jQuery not to set contentType 
    success: function (data) { 
     console.log(data) 
    }, 
    error: function(data) { 
     console.log(data) 
    } 
    }) 
} 
+0

对于初学者尝试 '变种FD = {}' –

回答

2

您只想发送FormData对象。为了你其他的键/值对append添加到该对象:

function admin_statistics_form_send(){ 
    var fd = new FormData($("#admin_statistics_form")[0]); 
    fd.append('api',"refresh_all"); 


    $.ajax({ 
    //async: true, // redundant since it is default and should never use `false` 
    beforeSend: function(){ 
    }, 
    url: "admin_statistics_api.php", 
    type: "POST", 
    data: fd, 
    dataType: "json", 
    processData: false, // tell jQuery not to process the data 
    contentType: false, // tell jQuery not to set contentType 
    success: function (data) { 
     console.log(data) 
    }, 
    error: function(data) { 
     console.log(data) 
    } 
    }) 
} 
+0

似乎已经奏效。所以FormData对象已经被序列化了,并且可以作为Json传递,而不需要我将它们串起来? –

+0

不,它不是json ...浏览器将在内部序列化它作为表单编码数据与默认表单提交相同的方式 – charlietfl