我想提交一个POST表单,其中包含一个textarea字段和一个输入字段(type =“checkbox”,任意/可变数量的复选框)网站通过jQuery的.ajax()。 PHP接收textarea数据并且ajax响应正确显示给用户。但是,似乎PHP没有收到复选框数据(是否检查过)。我怎样才能使这个工作?下面是我的代码有:通过jQuery将多个复选框数据发送到PHP ajax()
的HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
jQuery的:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
现在,PHP
$myField = htmlspecialchars($_POST['myField']));
if(isset($_POST['myCheckboxes']))
{
for ($i=0; $i < count($_POST['myCheckboxes']); $i++)
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
一切都很正常:当窗体提交新记录存储在我的数据库中,响应被回送到网页,但复选框数据未发送。我想知道哪些复选框已被选中。我已阅读.serialize(),JSON等,但没有一个工作。我必须在jQuery和PHP中序列化/ JSON吗?怎么样?使用复选框发送表单数据时,其中一种方法比另一种更好吗?我已经坚持了2天。任何帮助将不胜感激。提前致谢!
你不必担心表单元素 试试这个 http://stackoverflow.com/questions/19029703/jquery -using-ajax-to-send-data-and-save-in-php/19029778#19029778 – rohitcopyright 2013-09-26 16:17:54