使用ajax将数组发布到PHP

前端之家收集整理的这篇文章主要介绍了使用ajax将数组发布到PHP前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用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警告显示@H_404_10@[ “路由ID:testRoute”,@H_404_10@“客户编号:testCustID”@H_404_10@“stopnumber:teststopnumber”@H_404_10@“顾客:testCustomer”@H_404_10@“纬度:10”,@H_404_10@“经度:20”,@H_404_10@“时间戳:00:00:00”]

有谁看到我做错了什么?

注意:您的代码输出array()的主要原因是您在发送/处理异步(AJAX)请求之前重定向客户端 @H_404_10@基本上移动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",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调用之后重定向客户端,则必须将该表达式移动到第二个代码段^^中的成功回调函数(我记录响应的函数).

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

最后,请注意使用支持预处理语句的api(从而保护您免受大多数注入攻击),这并不意味着将未经检查的POST / GET数据串入查询比以前更安全……@H_404_10@结论:当您使用支持关键安全功能的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","database");//OO

MysqLi_select_db($MysqLi,"database");
//or
$MysqLi->select_db('database');

如果你愿意的话,检查文档以查看我将在这里使用的所有方法的程序对应物.我更喜欢OOP-API

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

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

> mysqli::prepare doc page@H_404_10@> mysqli_stmt::bind_result doc page获取数据时非常宝贵……@H_404_10@> quick tutorial 1@H_404_10@> Q&A-styled tutorial 2@H_404_10@>以防万一:PDO tutorial,too

猜你在找的Ajax相关文章