使用ajax将数组发布到PHP

时间:2013-04-16 16:05:11

标签: php javascript arrays posting

我在使用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", "stopnumber:teststopnumber", "customer:testCustomer", "latitude:10", "longitude:20", "timestamp:00:00:00"]

任何人都能看到我做错了什么?

2 个答案:

答案 0 :(得分:20)

注意 main 导致代码输出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的函数)。 / p>

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

最后,注意使用支持预准备语句的api(从而保护您免受大多数注入攻击),这并不意味着对未经检查的POST /将数据添加到查询中比以前更安全...
结论:当您使用支持关键安全功能的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

有关准备好的陈述的有用链接:

答案 1 :(得分: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发布数据

<?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'));
?>