[英]Pass an array to a php script using AJAX
I have a form that I would like to submit without refreshing the page, I am new to AJAX
and although I have managed this task passing a single value I'm not sure how to do this with an array. 我有一个无需刷新页面即可提交的表单,我是AJAX
新手,尽管我已经通过传递单个值来管理此任务,但我不确定如何使用数组来完成此任务。
The form input (displayed using a while
loop) 表单输入(使用while
循环显示)
<input type="hidden" name="user" value="<? echo $user_id; ?>" >
<input type="text" name="reason[][<? echo $row['reasonID']; ?>]"
size="25" value="<? echo $row['reason_name']; ?>"/>
<input type="submit" class="submit" value="Save"/>
The script 剧本
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
$(function() {
$(".submit").click(function() {
var dataString = '????';
$.ajax({
type: "POST",
url: "save_reasons.php",
data: dataString,
success: function(){
alert('yay');
}
});
return false;
});
});
</script>
save_reasons.php save_reasons.php
if(isset($_POST['save_reasons'])){
$user_id = $_POST['user'];
foreach($_POST['reason'] as $item=>$value)
{
if(is_array($value)){
foreach($value as $ID=>$reason)
{
$sql = "UPDATE gradeReason SET reason_name = '$reason' WHERE reasonID = $ID";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
}
}
else{
if($value !=''){
$sql = "INSERT INTO gradeReason (reason_userID, category, reason_name) VALUES ($user_id, 'positioning', '$value')";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
}
}
}
}
After doing some research I think using the datastring is the way forward but I am not sure how to using this with an array ( reason
) and the userID ( user
) and then use it in the PHP
script. 经过研究后,我认为使用数据字符串是前进的方向,但是我不确定如何将其与数组( reason
)和userID( user
)一起使用,然后在PHP
脚本中使用它。
Send your data as json. 将数据作为json发送。
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
On your server side script 在服务器端脚本上
<?php
$array = json_decode(file_get_contents("php://input"), true);
?>
Use jQuery serialize
function to pass your values. 使用jQuery serialize
函数传递您的值。
$.ajax({
type: "POST",
url: "save_reasons.php",
data: $('#myForm').serialize(),
success: function(){
alert('yay');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.