[英]jquery ajax not passing data to php?
我試圖將javascript Date對象傳遞給php,但是當我轉儲 $ _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
語句有助於避免混淆結果。 如果要包含此代碼,則不確定如何執行此操作。 正如我在評論中說的那樣,您沒有在Post中傳遞Date對象,因此您應該將所需的細節傳遞給PHP。
編輯
更新的代碼。 現在,您可以在控制台中查看data
,結果顯示為:
Running Post.
(Pacific Standard Time) is client TimeZone.
對於每個客戶,這當然是不同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.