gpt4 book ai didi

javascript - Ajax 表单提交给两个脚本

转载 作者:行者123 更新时间:2023-11-30 16:48:15 27 4
gpt4 key购买 nike

基本上我有一个表单,我想将变量传递给两个单独的 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>

最佳答案

最佳做法是使用一个后端脚本处理这两个调用。您可以使用数组返回 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);
});

关于javascript - Ajax 表单提交给两个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30928750/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com