我对 jquery 还比较陌生,所以我想知道使用 ajax 向 php 发送多个变量的最佳实践是什么。例如,我应该将变量发送到一个包中,例如:
$.ajax({
data:{
input: {x: 1, y: 2}
},
...
})
或将它们作为单独变量发送,例如:
$.ajax({
data:{
x: 1,
y: 2
},
...
})
使用其中一种相对于另一种是否有任何性能优势或任何其他类型的优势?
感谢您的宝贵时间, LL
最佳答案
当表单中有很多字段时,这个函数是最简单的.serialize()
<html>
<body>
<form action="#" id="formsend" method="post" name="formsend">
<input name="val1" id="val1">
<input name="val2" id="val2">
<input name="val3" id="val3">
......
</form>
<a href="javascript:;" id="btn_send" >Send</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type= "text/javascript"></script>
<script>
$( "#btn_send" ).click(function() {
$.ajax({
type: 'POST',
url: 'ajax/ImAjaxPhpFile.php',
data: $("#formsend").serialize(), // send all form
beforeSend: function(){
},
complete: function(){
},
success: function(a){
alert (a);
}
});
});
</script>
</body>
</html>
关于javascript - 使用ajax发送多个变量的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26265137/