源代码:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Content-Type: application/json');
echo json_encode($_POST);
exit(0);
}
?>
<html>
<head>
<title>Web Test</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
<form id="formTest">
<input name="username" value="admin" />
<input name="password" type="password" value="admin_pass" />
</form>
<script type="text/javascript">
$.ajaxSetup({
data: {role: 'admin'} //(I)
});
//Ajax to current page
$.ajax('test', {
method: 'post',
data: $('#formTest').serialize() //(II)
,success: function(res){
console.log(res);
}
});
</script>
</body>
</html>
我想通过 jQuery AJAX 发送表单数据,并将默认数据 (role=admin
) 附加到每个 AJAX 请求,但它无法按我想要的方式工作。
< br/>
我采取如下一些选择:
data: {role: 'admin'}//(I)
(默认数据)
data: $('#formTest').serialize()//(II)
(用于表单数据)
(这与上面的源代码完全相同)
=> 来自控制台的结果:{用户名:“admin”,密码:“admin_pass”}
所以,这个方法似乎行不通data: 'role=admin'//(I)
数据:$('#formTest').serialize()//(二)
(相同的 URL 编码格式)
=> 同上data: [{name: 'role', value: 'admin'}]//(I)
数据:$('#formTest').serializeArray()//(二)
(相同的serializeArray格式)
=> 同上数据:{角色:'admin'}//(I)
data: {用户名: 'admin', 密码: 'admin_pass'}//(二)
=> 这个方法有效!但是没有内置 jQuery 方法可以将表单数据转换为这样的对象。我必须使用“第三方”解决方案,使用$('#formTest').serializeObject()
(来自 here )。
那么,有没有办法只用 jQuery 来解决这个问题呢?
JQuery 提供 ajaxSetup
和 serialize/serializeArray
方法,但它们似乎不能很好地配合。
最佳答案
为什么不附加一个带有所需数据的变量?
<html>
<head>
<title>Web Test</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form id="formTest">
<input name="username" value="admin" />
<input name="password" type="password" value="admin_pass" />
</form>
<script>
var theRole = '&role=admin';
//Ajax to current page
$.ajax('test.php', {
method: 'post',
data: $('#formTest').serialize() + theRole,
success: function(res) {
console.log(res);
}
});
</script>
</body>
</html>
编辑
另一种方法,使用ajaxSetup()
<html>
<head>
<title>Web Test</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form id="formTest">
<input name="username" value="admin" />
<input name="password" type="password" value="admin_pass" />
</form>
<script>
$.ajaxSetup({ data: {role: 'admin'} });
//Ajax to current page
$.ajax('test.php?' + $('#formTest').serialize(), {
method: 'post',
success: function(res) {
console.log(res);
}
});
</script>
</body>
</html>
然后必须使用 json_encode( $_REQUEST ) 来代替。
<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
header( 'Content-Type: application/json' );
echo json_encode( $_REQUEST );
}
?>
关于javascript - 使用内置 jQuery 在默认设置下发送 ajax 表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067204/