2017-06-20 149 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

相关问题