php 使用ajax将数组发布到PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16041835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Posting Array to PHP using ajax
提问by EzAnalyst
I'm having issues posting an Array to a PHP page using AJAX. I've been using this questionas guidance, but for whatever reason I still can't get it to work. From what I can tell by using print_r($_POST)
, I am posting an empty Array, but on the HTML/Javascript page I use an alert to see that the Array has been filled. The post is working because it inputs blank values into a MySQL database on post, but I can't figure out why it is passing an empty Array. The code is as follows:
我在使用 AJAX 将数组发布到 PHP 页面时遇到问题。我一直在使用这个问题作为指导,但无论出于何种原因,我仍然无法让它发挥作用。据我所知print_r($_POST)
,我发布了一个空数组,但在 HTML/Javascript 页面上,我使用警报来查看数组已被填充。该帖子正在运行,因为它在发布时将空白值输入到 MySQL 数据库中,但我不知道它为什么传递一个空数组。代码如下:
Javascript:
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:
<?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)
only displays Array() on the php page while the jsonString alert on the javascript page shows
["routeID:testRoute",
"custID:testCustID",
"stopnumber:teststopnumber",
"customer:testCustomer",
"latitude:10",
"longitude:20",
"timestamp:00:00:00"]
print_r($_POST)
仅在 php 页面上显示 Array() 而在 javascript 页面上显示 jsonString 警报
["routeID:testRoute",
"custID:testCustID",
"stopnumber:teststopnumber",
"customer:testCustomer",
"latitude:10",
"longitude:20",
"timestamp:00:00:00"]
Anyone see what I'm doing wrong?
有人看到我做错了什么吗?
回答by Elias Van Ootegem
Note:The maincause for your code to output array()
is the fact that you're redirecting the client before the asynchronous (AJAX) request has been sent/processed
Basically move window.location = "AddtoDatabase.php";
to the success callback, as mentioned further down.
注:在主要的原因为您的代码输出array()
是您要重定向客户端的事实异步(AJAX)请求已发送/处理前
基本上移动window.location = "AddtoDatabase.php";
到成功回调,如提及进一步下跌。
First problem: Instead of using an array, you should use an object literal (~= assoc array in php).
第一个问题:您应该使用对象字面量(php 中的 ~= assoc 数组)而不是使用数组。
To do so, change this bit:
为此,请更改此位:
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;
And write this, instead:
并写下这个,而不是:
var dataObject = { routeID: routeID,
custID: custID,
stopnumber: stopnumber
customer: customer,
latitude: lat,
longitute: lng,
timestamp: timeStamp};
There's nothing more too it. To finish off, just send the data like so:
也没有什么了。最后,只需像这样发送数据:
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);
}
});
Secondly, your postData
function redirects the client before the AJAX request has been sent! After the call to $.ajax
, you have a window.location = "AddtoDatabase.php";
statement in your code. If you want the client to be redirected after the ajax call, you will have to move that expression to your success
callback function (the one where I log the response
) in the second snippet ^^.
其次,您的postData
函数会在发送 AJAX 请求之前重定向客户端!在调用 之后$.ajax
,您window.location = "AddtoDatabase.php";
的代码中有一条语句。如果您希望在 ajax 调用后重定向客户端,则必须将该表达式移动到第二个代码段 ^^ 中的success
回调函数(我记录 的那个函数response
)。
When you've changed all this, your $_POST
variable should look about right. If not, print out the $_REQUEST
object and see what the response of an ajax call is then.
当你改变了这一切后,你的$_POST
变量应该看起来是正确的。如果没有,则打印出该$_REQUEST
对象,然后查看 ajax 调用的响应是什么。
Lastly, pleasebe aware that using an api that supports prepared statements (and thus protects you against mostinjection attacks), that doesn't mean stringing unchecked POST/GET data into a query is any safer than it used to be...
Bottom line: When you use an API that supports critical safety features such as prepared statements use those features.
最后,请注意,使用支持预处理语句的 api(从而保护您免受大多数注入攻击),这并不意味着将未经检查的 POST/GET 数据串入查询比以前更安全......
底部行:当您使用支持关键安全功能(例如准备好的语句)的 API 时,请使用这些功能。
Just to be absolutely clear, and complete, here's a slightly reworked version of the PHP code, too:
为了绝对清楚和完整,这里还有一个稍微修改过的 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');
Check the docs to see the procedural counterpart of all methods I'll be using from here on end, if you want. I prefer the OOP-API
如果需要,请查看文档以查看我将从这里开始使用的所有方法的程序对应物。我更喜欢 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
Useful links on prepared statements:
有关准备好的语句的有用链接:
mysqli::prepare
doc pagemysqli_stmt::bind_result
doc pageis invaluable when it comes to fetching data...- quick tutorial 1
- Q&A-styled tutorial 2
- Just in case: a
PDO
tutorial, too
mysqli::prepare
文档页面mysqli_stmt::bind_result
doc 页面在获取数据方面是无价的...- 快速教程 1
- 问答式教程2
- 以防万一:还有
PDO
教程
回答by Erdem Ece
you should use serialize. then......
你应该使用序列化。然后......
<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>
than in php take data with post
比在 php 中使用 post 获取数据
<?php
$routeID = $_POST['routeID'];
$custID = $_POST['custID'];
$stopnumber = $_POST['stopnumber'];
$customer = $_POST['customer'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$timestamp = $_POST['timestamp'];
?>
and display with json encode. this way you can display errors
并以 json 编码显示。这样你就可以显示错误
<?php
if(true)
echo json_encode(array('redirect'=>'true', 'message'=>'form submitted'));
else
echo json_encode(array('redirect'=>'false', 'message'=>'form not submited'));
?>