我在使用 AJAX 将数组发布到 PHP 页面时遇到问题。我一直在使用这个问题作为指导,但无论出于何种原因,我仍然无法让它发挥作用。据我所知print_r($_POST)
,我发布了一个空数组,但在 HTML/Javascript 页面上,我使用警报来查看数组已被填充。该帖子正在工作,因为它在帖子中将空白值输入到 MySQL 数据库中,但我无法弄清楚它为什么传递一个空数组。代码如下:
Javascript:
<script type="text/javascript">
var routeID = "testRoute";
var custID = "testCustID";
var stopnumber = "teststopnumber";
var customer = "testCustomer";
var lat = 10;
var lng = 20;
var timeStamp = "00:00:00";
var dataArray = new Array(7);
dataArray[0]= "routeID:" + routeID;
dataArray[1]= "custID:" + custID;
dataArray[2]= "stopnumber:" + stopnumber;
dataArray[3]= "customer:" + customer;
dataArray[4]= "latitude:" + lat;
dataArray[5]= "longitude:" + lng;
dataArray[6]= "timestamp:" + timeStamp;
var jsonString = JSON.stringify(dataArray);
function postData(){
$.ajax({
type: "POST",
url: "AddtoDatabase.php", //includes full webserver url
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
window.location = "AddtoDatabase.php"; //includes full webserver url
}
alert(JSON.stringify(dataArray))
</script>
PHP:
<?php
print_r($_POST);
$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
$mysqli= new mysqli("fdb5.biz.nf","username","password","database");
mysqli_select_db($mysqli,"database");
$sql = "INSERT INTO Locations (routeID, custID, stopnumber, customer, latitude, longitude, timestamp) VALUES " .
"('$routeID','$custID','$stopnumber','$customer','$latitude','$longitude','$timestamp')";
mysqli_query($mysqli, $sql);
$error = mysqli_error($mysqli);
echo $error;
?>
print_r($_POST)
仅在 php 页面上显示 Array() 而 javascript 页面上的 jsonString 警报显示
["routeID:testRoute",
"custID:testCustID",
"stopnumber:teststopnumber",
"customer:testCustomer",
"latitude:10",
"longitude:20",
"timestamp:00:00:00"]
有人看到我做错了什么吗?