发布数组到PHP用ajax [英] Posting Array to PHP using ajax
问题描述
我有张贴阵列使用AJAX PHP页面的问题。我一直在使用 href=\"http://stackoverflow.com/questions/9001526/send-array-with-ajax-to-php-script\">这个问题为导向,但不管是什么原因我仍然无法得到它的工作。从我可以通过告诉的print_r($ _ POST)
,我张贴空数组,但对HTML / JavaScript页面我用警报看到阵列被填满。该职位的工作,因为它输入空值插入后一个MySQL数据库,但我想不通为什么它是传递一个空数组。在code是如下:
I'm having issues posting an Array to a PHP page using AJAX. I've been using this question as 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:
使用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
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
客户ID:testCustID
stopnumber:teststopnumber
顾客:testCustomer
北纬:10,
经度:20,
时间戳:00:00:00]
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"]
任何人看到我在做什么错了?
Anyone see what I'm doing wrong?
推荐答案
注意:的主的原因为您的code输出阵列()
是你异步重定向之前在客户端的的事实(AJAX)请求已发送/处理的
基本上移动 window.location的=AddtoDatabase.php;
来的成功回调,如前所述进一步下跌
Note: The main cause 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.
第一个问题:除了使用数组,你应该使用对象文本(〜= assoc命令数组中的PHP)
First problem: Instead of using an array, you should use an object literal (~= assoc array in php).
要做到这一点,改变该位:
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);
}
});
其次,你的 POSTDATA
函数重定向AJAX请求已发送之前,客户端! ,调用 $阿贾克斯
之后,你有一个 window.location的=AddtoDatabase.php;在
您的发言code。如果你想在客户端Ajax调用之后被重定向,你必须到前pression移动到你的成功
回调函数(一个在我的日志响应
)的第二个片断^^。
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'll have to move that expression to your success
callback function (the one where I log the response
) in the second snippet ^^.
当你已经改变了这一切,你的 $ _ POST
变量应该是正确的。如果不是,打印出 $ _ REQUEST
对象,看看Ajax调用的响应是什么呢。
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.
最后的请的注意,使用支持$ P $的API ppared语句(从而保护您免受最注入攻击),这并不意味着串起选中POST / GET数据到一个查询比以前要更加安全......
底线:当您使用支持关键的安全功能,如$ P $的API ppared语句的使用这些特性的
Lastly, please be aware that using an api that supports prepared statements (and thus protects you against most injection 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.
只是要绝对清晰和完整,这里的PHP code的一个稍微返工的版本,也:
Just to be absolutely clear, and complete, here's a slightly reworked version of the PHP code, too:
$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');
检查文档看到的所有方法的程序对应,我会从这里被使用在最后,如果你想要的。我preFER面向对象的API
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
//making a prepared statement:
$query = 'INSERT INTO Locations
(routeID, custID, stopnumber, customer, latitude, longitude, timestamp) VALUES
(?,?,?,?,?,?,?)';
if (!($stmt = $mysql->prepare($query)))
{
echo $quer.' 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
在prepared报表相关链接:
Useful links on prepared statements:
-
的mysqli :: prepare
文档页面 - <$c$c>mysqli_stmt::bind_result$c$c>文档页面是非常宝贵的,当涉及到获取数据...
- quick教程1
- Q&安培; A风格教程2
- 以防万一:一个
PDO
的教程,太
mysqli::prepare
doc pagemysqli_stmt::bind_result
doc page is invaluable when it comes to fetching data...- quick tutorial 1
- Q&A-styled tutorial 2
- Just in case: a
PDO
tutorial, too
这篇关于发布数组到PHP用ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!