2017-07-26 57 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