我试图将 javascript Date 对象传递给 php,但是当我 dump $_POST 时,它返回空数组或字符串。我在同一个文件中执行此操作,所以在 file.php是php代码和javascript代码。 javascript 也显示一切都是正确的,因为它在成功函数中发出警报。
<?php
var_dump($_POST); //returns empty array
var_dump($_POST['zone']); //returns null
?>
<script type="text/javascript">
var date = new Date();
$.ajax({
type:'POST',
data: {zone : date},
success: function(data){
alert("test"); //this runs normally
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
</script>
最佳答案
这是我在 phpfiddle.org 上测试的一些代码:
<?php
if(isset($_POST['zone'])){
// Only runs when there is a Post for 'zone'
//var_dump($_POST);
echo $_POST['zone'];
} else{
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
var date = new Date();
function postZone(){
$.ajax({
type:'POST',
data: {zone : date},
success: function(data){
console.log(data);
//alert("test"); //this runs normally
$("#zone").html(data.substring(data.indexOf("(")) + " is client TimeZone.");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
postZone();
</script>
Running Post.
<div id='zone'></div>
</body>
</html>
<?php
}
?>
这是我在帖子结果中看到的内容:
array(1) {
["zone"]=>
string(57) "Mon Jan 18 2016 09:44:17 GMT-0800 (Pacific Standard Time)"
}
string(57) "Mon Jan 18 2016 09:44:17 GMT-0800 (Pacific Standard Time)"
添加 if
语句有助于避免结果混淆。如果包含此代码,不确定您将如何执行此操作。正如我在评论中所说,您没有在帖子中传递 Date 对象,因此您应该将所需的具体信息传递给 PHP。
编辑
更新了代码。您现在可以在控制台中看到数据
,结果显示为:
Running Post.
(Pacific Standard Time) is client TimeZone.
当然,每个客户的情况都会有所不同。
关于javascript - jquery ajax 没有将数据传递给 php?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860118/