我一直在尝试解析$ _POST数据以检索一系列价格和id编码。有人能指出我正确的方向吗?这就是我所拥有的:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
//e.preventDefault();
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: '/price-update.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function () {
alert('form was submitted');
}
});
});
});
</script>
发送的$ _POST数据示例:
?提交=提交+变更&安培;价格%5B%5D = 11和ID%5B%5D = 6&安培;价格%5B%5D = 22和ID%5B%5D = 5&安培;价格%5B%5D = 33&安培; ID%5B%5D = 3及价格%5B%5D = 44和ID%5B%5D = 2及价格%5B%5D = 55和ID%5B%5D = 8
<?php
//Part of my price-update.php file
if($_POST) {
$Values = array();
parse_str($_POST, $Values);
for($i = 0; $i < count($Values['price']); $i++) {
$price_update = "UPDATE prices SET price=".$Values['price'][$i]." WHERE id=".$Values['id'][$i];
$send_update = $instance->query($price_update);
}
}
?>
我收到成功消息弹出窗口,提示表单已提交。但是数据库中没有更改任何值。
答案 0 :(得分:0)
我已经改变了你的代码,并添加了一些php文件,它将一些值返回到前端,所以示例已经完成。
html文件:
<form id="form">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
javascript文件:
$(function () {
$('#form').on('submit', function (e) { // get element with id="form"
e.preventDefault(); // prevent default form submission
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: '/price-update.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
done: function (res) {
console.log('res', res);
alert('form was submitted');
}
});
});
});
php文件:
<?php
if($_POST['bar']) {
$values = array();
foreach ($_POST as $key => $value) {
$values[$key] = $value; // do something with values (for example put them to array)
}
echo json_encode($values); // return those values to the frontend
}
您可以查看更详细的说明 here