注意:您的代码输出array()的主要原因是您在发送/处理异步(AJAX)请求之前重定向客户端
基本上移动window.location =“AddtoDatabase.PHP”;成功回调,如下所述.
第一个问题:您应该使用对象文字(在PHP中为〜= assoc数组),而不是使用数组.
为此,请更改此位:
var dataArray = new Array(7);//<== NEVER do this again,btw
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 dataObject = { routeID: routeID,custID: custID,stopnumber: stopnumber
customer: customer,latitude: lat,longitute: lng,timestamp: timeStamp};
没有什么比它更重要了.要完成,只需发送如下数据:
function postData()
{
$.ajax({ type: "POST",data: dataObject,//no need to call JSON.stringify etc... jQ does this for you
cache: false,success: function(resopnse)
{//check response: it's always good to check server output when developing...
console.log(response);
alert('You will redirect in 10 seconds');
setTimeout(function()
{//just added timeout to give you some time to check console
window.location = 'AddtoDatabase.PHP';
},10000);
}
});
其次,postData函数在发送AJAX请求之前重定向客户端!在调用$.ajax之后,你有一个window.location =“AddtoDatabase.PHP”;代码中的语句.如果您希望在ajax调用之后重定向客户端,则必须将该表达式移动到第二个代码段^^中的成功回调函数(我记录响应的函数).
当你改变了所有这些后,你的$_POST变量看起来应该是正确的.如果没有,打印出$_REQUEST对象,然后查看ajax调用的响应.
最后,请注意使用支持预处理语句的api(从而保护您免受大多数注入攻击),这并不意味着将未经检查的POST / GET数据串入查询比以前更安全……
结论:当您使用支持关键安全功能的API(如预准备语句)时,请使用这些功能.
只是为了绝对清楚,完整,这里也是一个稍微改进的PHP代码版本:
$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
//you're connecting OO-style,why do you switch to procedural next?
//choose one,don't mix them,that makes for fugly code:
$MysqLi = MysqLi_connect('fdb5.biz.nf','username','password','database');//procedural
//or,more in tune with the times:
$MysqLi= new MysqLi("fdb5.biz.nf","database");//OO
MysqLi_select_db($MysqLi,"database");
//or
$MysqLi->select_db('database');
如果你愿意的话,检查文档以查看我将在这里使用的所有方法的程序对应物.我更喜欢OOP-API
//making a prepared statement:
$query = 'INSERT INTO Locations
(routeID,timestamp) VALUES
(?,?,?)';
if (!($stmt = $MysqLi->prepare($query)))
{
echo $query.' Failed to prepare';
exit();
}
$stmt->bind_param('s',$routeID);
$stmt->bind_param('s',$custID);
//and so on
$stmt->bind_param('d',$latitude);//will probably be a double
$stmt->execute();//query DB
准备好的陈述上有用的链接