我有nex代码。
<input name='uno[]' value='gonzalo' />
<input name='uno[]' value='marcos'/>
<input name='uno[]' value='martin'/>
<input name='uno[]' value='claudio'/>
如果y将表单发送到Ejample procesa.php,我可以用这种方式获取变量。
$variable=$_POST['uno'];
echo $ variable [2] // martin
但是,我如何通过ajax发送变量?
有人帮忙吗?
答案 0 :(得分:0)
将数据放入数组
var uno = [];
$('input[name="uno[]"]').each( function() {
uno.push(this.value);
});
并发送
$.ajax({
type: "POST",
url: "procesa.php",
data: {uno: uno}
})
答案 1 :(得分:0)
另一种管理表单所有字段的解决方案。
<强> form.html 强>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="procesa.php" id="myUno" method="post">
<input name='uno[0]' value='gonzalo' /><br/>
<input name='uno[1]' value='marcos'/><br/>
<input name='uno[2]' value='martin'/><br/>
<input name='uno[3]' value='claudio'/><br/>
<select name="uno[4]" id="">
<option value="">....</option>
<option value="opt1">opt1</option>
<option value="opt2" selected>opt2</option>
<option value="opt3">opt3</option>
<option value="opt4">opt4</option>
</select><br/>
<textarea name="uno[5]" id="" cols="30" rows="4">test content!!</textarea><br/>
<label for="checkbox_1">checkbox 1</label>
<input type="checkbox" name="uno[6]" id="checkbox_1" value="checkbox_1" checked="checked"><br/>
<label for="apple">Apple</label>
<input type="radio" id="apple" name="uno[7]" value="apple">
<label for="orange">Orange</label>
<input type="radio" id="orange" name="uno[7]" value="orange" checked="checked">
<br/>
<input type="submit" id="form_submit">
</form>
<div id="result"></div>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<script src="process.js"></script>
</body>
</html>
<强> procesa.php 强>
<?php
$uno = $_POST['uno'];
var_dump($_POST);
<强> process.js 强>
$(function() {
$( "#myUno" ).submit(function( event ) {
event.preventDefault();//
//we get the data in a single table through our function below
var formData = $('#myUno').serializeAssoc();
console.log(formData);
$.ajax({
type: "POST",
url: "procesa.php",
data: { uno: formData.uno }
})
.done(function( data ) {
$('#result').html(data); //displays the response returned. This is used to debug if necessary
});
});
});
$.fn.serializeAssoc = function() {
var data = {};
$.each( this.serializeArray(), function( key, obj ) {
var a = obj.name.match(/(.*?)\[(.*?)\]/);
if(a !== null)
{
var subName = a[1];
var subKey = a[2];
if( !data[subName] ) data[subName] = [ ];
if( data[subName][subKey] ) {
if( $.isArray( data[subName][subKey] ) ) {
data[subName][subKey].push( obj.value );
} else {
data[subName][subKey] = [ ];
data[subName][subKey].push( obj.value );
}
} else {
data[subName][subKey] = obj.value;
}
} else {
if( data[obj.name] ) {
if( $.isArray( data[obj.name] ) ) {
data[obj.name].push( obj.value );
} else {
data[obj.name] = [ ];
data[obj.name].push( obj.value );
}
} else {
data[obj.name] = obj.value;
}
}
});
return data;
};
我发现此插件 $。fn.serializeAssoc 效果良好here