基本上我有一个表单,我想将变量传递给两个单独的PHP脚本,以便在提交时进行处理。我所做的工作似乎对我的目的很好,我只是想知道是否有办法在一个jquery脚本中执行此操作,而不是像我一样重复脚本和更改URL。或者是iv的方式很好吗?无法在谷歌上找到许多这种用法的例子,但也许我没有找到正确的东西。另外,如果我做一些不好的做法,请告诉我,我对Ajax很新,我所遵循的每个教程似乎都有不同的做法。
<script>
$(document).ready(function(){
$('#sform').submit(function(){
// show that something is loading
$('#response').html("<b>Loading response...</b>");
/*
* 'post_receiver.php' - where you will pass the form data
* $(this).serialize() - to easily read form data
* function(data){... - data contains the response from post_receiver.php
*/
$.ajax({
type: 'POST',
url: 'move_to_lease.php',
data: $(this).serialize()
})
.done(function(data){
// show the response
$('#response').html(data);
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
</script>
<script>
$(document).ready(function(){
$('#sform').submit(function(){
// show that something is loading
$('#txtHint').html("<b>Loading response...</b>");
/*
* 'post_receiver.php' - where you will pass the form data
* $(this).serialize() - to easily read form data
* function(data){... - data contains the response from post_receiver.php
*/
$.ajax({
type: 'POST',
url: 'show_lease_sub.php',
data: $(this).serialize()
})
.done(function(data){
// show the response
$('#txtHint').html(data);
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
</script>
答案 0 :(得分:2)
最佳做法是使用一个后端脚本处理这两个调用。您可以通过使用数组返回2个单独的响应。 Protip - 写一堂课。
ajax.php
class leaseStuff{
public static function moveToLease($data){
// add code from move_to_lease.php, change $_POST to $data
}
public static function showLeaseSub($data){
// add code from show_lease_sub.php, change $_POST to $data
}
}
echo json_encode(array(
"moveToLease"=>leaseStuff::moveToLease($_POST),
"showLeaseSub"=>leaseStuff::showLeaseSub($_POST)
));
然后,您可以将Ajax合并为一个调用:
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $(this).serialize()
}).done(function(data){
data = JSON.parse(data);
$('#response').html(data.moveToLease);
$('#txtHint').html(data.showLeaseSub);
});
答案 1 :(得分:0)
尝试使用您的网址迭代数组:
$('#sform').submit(function () {
var urls = [
{
"url": "move_to_lease.php",
"response_id": "#response"
},
{
"url": "show_lease_sub.php",
"response_id": "#txtHint"
}
]
for (var k in urls) {
$(urls[k].response_id).html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: urls[k].url,
data: $(this).serialize()
}).done(function (data) {
$(urls[k].response_id).html(data);
}).fail(function () {
alert("Posting failed.");
});
}
return false;
});
<强>更新强>
根据您提供的图片 IMAGE ,您需要进行两次不同的AJAX调用。
提交表单时: - &gt;将信息保存到DB - &gt;获取信息以更新显示
更改选择下拉列表时: - &gt;从数据库中获取信息 - &gt;获取信息以更新显示