使用ajax将数组发布到PHP

EzA*_*yst 8 javascript php arrays posting

我在使用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>
Run Code Online (Sandbox Code Playgroud)

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;
?>
Run Code Online (Sandbox Code Playgroud)

print_r($_POST) 只显示php页面上的Array(),而javascript页面上的jsonString警告显示 ["routeID:testRoute", "custID:testCustID", "stopnumber:teststopnumber", "customer:testCustomer", "latitude:10", "longitude:20", "timestamp:00:00:00"]

有谁看到我做错了什么?

Eli*_*gem 20

注:主要的代码输出的原因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; 
Run Code Online (Sandbox Code Playgroud)

写下这个,而不是:

var dataObject = { routeID: routeID,
                   custID:  custID,
                   stopnumber: stopnumber
                   customer: customer,
                   latitude: lat,
                   longitute: lng,
                   timestamp: timeStamp};
Run Code Online (Sandbox Code Playgroud)

没有什么比它更重要了.要完成,只需发送如下数据:

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);
             }
    });
Run Code Online (Sandbox Code Playgroud)

其次,您的postData函数在发送AJAX请求之前重定向客户端!在调用之后$.ajax,您window.location = "AddtoDatabase.php";的代码中有一个语句.如果您希望在ajax调用之后重定向客户端,则必须将该表达式移动到第二个代码段^^中的success回调函数(我记录的那个response).

当你改变了这一切后,你的$_POST变量看起来应该是正确的.如果没有,打印出$_REQUEST对象,然后查看ajax调用的响应.

最后,注意,使用支持预处理语句(从而保护您免受一个API 注入攻击),这并不意味着串选中POST/GET数据到一个查询任何安全比以前要...
底部line:当您使用支持关键安全功能的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');
Run Code Online (Sandbox Code Playgroud)

如果需要,检查文档以查看我将在这里使用的所有方法的过程对应物.我更喜欢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
Run Code Online (Sandbox Code Playgroud)

准备好的陈述上有用的链接