2017-06-20 57 views
-1

這js jQuery腳本正確格式化表單數據到一個對象併發送到我的PHP代碼。jQuery ajax POST請求到Apache PHP服務器沒有收到數據

$("#formSignup").submit(function(e){ 
    // Map the array into a properly formatted object 
    var data = {}; 
    $.map($(this).serializeArray(),function(n, i){ 
     data[n.name] = n.value; 
    }); 
    // Send the http request 
    $.ajax({ 
     type: "POST", 
     url: "api/signup.php", 
     data: JSON.stringify(data), 
     contentType: "application/json", 
     success: function(response){ 
      //console.log(JSON.parse(response)); 
      console.log(response); 
     }, 
     failure: function(err){ 
      console.error(err); 
     } 
    }); 
    e.preventDefault(); // Don't submit defaultly 
}); 

但是PHP無法接收數據。 print_r($_POST)將打印一個空數組,並且值不可訪問。它沒有得到來自錯誤文件的迴應。

考慮到Mozilla開發控制檯記錄的XmlHttpRequest明確發佈了JSON數據,這非常奇怪。

XHR

enter image description here

其他問題已被指出通過對服務器進行重定向回答。然而,我還沒有做任何事情,這些設置,我得到了後工作在同一臺服務器與我自己的功能後發出的請求。

+2

你有你的PHP代碼樣本嗎? – Nick

+0

@尼克沒有什麼特別的。 $ _POST變量只是空的。 –

+0

PHP無法將JSON解碼爲'$ _POST'。如果你真的想發送數據爲JSON,你必須使用'json_decode(file_get_contents(「php:// input」))' – Barmar

回答

2

從您的ajax對象中刪除contentType屬性。

要序列化數據只需使用$(this).serialize()

$("#formSignup").submit(function(e){ 

    var data = $(this).serialize(); 

    // Send the http request 
    $.ajax({ 
     type: "POST", 
     url: "api/signup.php", 
     data: data, 
     success: function(response){ 
      console.log(response); 
     }, 
     failure: function(err){ 
      console.error(err); 
     } 
    }); 
    e.preventDefault(); // Don't submit defaultly 
}); 

之後,您應該能夠成功地在$_POST變量中看到您的數據。

+0

這就是我想避免 –

+0

@JohanSundman如果你需要用php讀取你的數據服務器端,那麼這是一條路。服務器端你可以做'json_encode()'。 – loelsonk

+0

當你使用'type:「post」'時,數據不會放入查詢字符串中,它會被放入POST數據中。 – Barmar