8

我在使用 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"]

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

4

2 回答 2

21

注意:您的代码输出的主要原因是您在发送/处理异步(AJAX)请求之前array()重定向客户端 基本上移动到成功回调,如下所述。
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,这并不意味着将未经检查的 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","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

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

于 2013-04-16T16:15:21.070 回答
0

你应该使用序列化。然后......

<script>

jQuery(document).ready(function($){
/* attach a submit handler to the form */
$("#submit").click( function(event) {

/* stop form from submitting normally */
 event.preventDefault();

 /*clear result div*/
 $("#loginresponse").html('');

 /* use serialize take everthing into array */
    var frmdata = $("#formname").serialize();

$.ajax({
  url: "/file.php",
  type: "post",
  dataType: "json",
  data: frmdata,
  success: function(data, textStatus){
    if(data.redirect == 'true'){
       $('#formresponse').html(data.message);
      return true;
    }else{
      $('#formresponse').html(data.message);
      return false;
    }
  },
  error:function(){
      $("#formresponse").html('error');
  }
});
});
}); 

</script>

比在 php 中使用 post 获取数据

<?php
$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
?>

并使用 json 编码显示。这样你就可以显示错误

<?php 

if(true)
    echo json_encode(array('redirect'=>'true', 'message'=>'form submitted'));
else
    echo json_encode(array('redirect'=>'false', 'message'=>'form not submited'));
?>
于 2013-04-16T16:19:42.997 回答