首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >使用ajax将数组发布到PHP

使用ajax将数组发布到PHP
EN

Stack Overflow用户
提问于 2013-04-17 00:05:11
回答 2查看 57.2K关注 0票数 8

我在使用AJAX将数组发送到PHP页面时遇到问题。我一直在使用this question作为指导,但无论出于什么原因,我仍然不能让它工作。从我使用print_r($_POST)可以看出的是,我发布了一个空数组,但是在HTML/Javascript页面上,我使用一个警告来查看数组已被填充。post之所以起作用,是因为它在post时将空值输入到MySQL数据库中,但我不明白它为什么要传递一个空数组。代码如下:

Javascript:

代码语言:javascript
代码运行次数:0
运行
复制
<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:

代码语言:javascript
代码运行次数:0
运行
复制
<?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页面上显示数组(),而javascript页面上的jsonString警告显示["routeID:testRoute", "custID:testCustID", "stopnumber:teststopnumber", "customer:testCustomer", "latitude:10", "longitude:20", "timestamp:00:00:00"]

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-17 00:15:21

注意:导致代码输出array()的主要原因是您在发送/处理异步(AJAX)请求之前重定向了客户端

基本上,将window.location = "AddtoDatabase.php";移到success回调,正如前面提到的那样。

第一个问题:不应该使用数组,而应该使用对象文字(php中的~= assoc数组)。

要执行此操作,请更改此位:

代码语言:javascript
代码运行次数:0
运行
复制
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; 

改为这样写:

代码语言:javascript
代码运行次数:0
运行
复制
var dataObject = { routeID: routeID,
                   custID:  custID,
                   stopnumber: stopnumber
                   customer: customer,
                   latitude: lat,
                   longitute: lng,
                   timestamp: timeStamp};

没有比这更多的了。要完成此操作,只需像这样发送数据:

代码语言:javascript
代码运行次数:0
运行
复制
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代码的一个稍微修改过的版本:

代码语言:javascript
代码运行次数:0
运行
复制
$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

代码语言:javascript
代码运行次数:0
运行
复制
//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

有关预准备语句的有用链接:

当涉及到在case: A PDO tutorial, too中获取data...

票数 20
EN

Stack Overflow用户

发布于 2013-04-17 00:19:43

您应该使用serialize。然后......

代码语言:javascript
代码运行次数: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获取数据。

代码语言:javascript
代码运行次数:0
运行
复制
<?php
$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
?>

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

代码语言:javascript
代码运行次数:0
运行
复制
<?php 

if(true)
    echo json_encode(array('redirect'=>'true', 'message'=>'form submitted'));
else
    echo json_encode(array('redirect'=>'false', 'message'=>'form not submited'));
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16041835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档