gpt4 book ai didi

php - 使用ajax将数组发布到PHP

转载 作者:可可西里 更新时间:2023-11-01 12:27:05 26 4
gpt4 key购买 nike

我在使用 AJAX 将数组发布到 PHP 页面时遇到问题。我一直在使用 this question作为指导,但无论出于何种原因,我仍然无法让它发挥作用。通过使用 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",
“停止编号:测试停止编号”,
“客户:测试客户”,
“纬度:10”,
“经度:20”,
“时间戳:00:00:00”]

有人看到我做错了什么吗?

最佳答案

注意:您的代码输出 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",
url: "AddtoDatabase.php",
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 调用之后被重定向,您必须将该表达式移动到您的 success 回调函数(我在其中记录 response 的函数)第二个片段 ^^。

当您更改了所有这些内容后,您的 $_POST 变量应该看起来是正确的。如果不是,则打印出 $_REQUEST 对象并查看 ajax 调用的响应。

最后,注意使用支持准备语句的 api(从而保护您免受大多数注入(inject)攻击),这并不意味着串接未经检查的 POST/GET data into a query 比以前更安全...
底线:当您使用支持关键安全功能(例如准备好的语句)的 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","username","password","database");//OO

mysqli_select_db($mysqli,"database");
//or
$mysqli->select_db('database');

如果需要,请检查文档以查看我将在此处使用的所有方法的程序对应部分。我更喜欢 OOP-API

//making a prepared statement:
$query = 'INSERT INTO Locations
(routeID, custID, stopnumber, customer, latitude, longitude, 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

准备好的语句的有用链接:

关于php - 使用ajax将数组发布到PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16041835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com