同一ajax调用中有多个url?这可能吗

Multiple url in same ajax call?is this possible?

本文关键字:url 调用 ajax 同一      更新时间:2023-09-26

我可以使用ajax调用将数据发送到多个页面吗?我不想为此使用另一个ajax调用。

样本代码:

 $.ajax({
     type: 'POST',
     url: '../services/form_data.php', //can I send data to multiple url with same ajax call.
     data: {
         answer_service: answer,
         expertise_service: expertise,
         email_service: email,
     },
     success: function (data) {
         $(".error_msg").text(data);
     }
 });

对于来自多个页面的一个请求,不能使用相同的代码。

但是你可以发送两个请求。它可以通过复制粘贴ajax代码来完成,也可以通过构建一个函数来获取URL并使用该URL 发送请求

function sendMyAjax(URL_address){
    $.ajax({
         type: 'POST',
         url: URL_address,
         data: {
             answer_service: answer,
             expertise_service: expertise,
             email_service: email,
         },
         success: function (data) {
             $(".error_msg").text(data);
         }
     });
};

您只需要$.each和$.ajax 的双参数形式

var urls = ['/url/one','/url/two', ....];
$.each(urls, function(i,u){ 
     $.ajax(u, 
       { type: 'POST',
         data: {
            answer_service: answer,
            expertise_service: expertise,
            email_service: email,
         },
         success: function (data) {
             $(".error_msg").text(data);
         } 
       }
     );
});

注意:成功回调生成的消息将相互覆盖,如图所示。您可能希望在success函数中使用$('#someDiv').append()或类似函数。

单个AJAX请求只能与一个URL对话,但您可以为不同的URL创建多个AJAX请求,它们将同时完成工作-您不需要等待一个请求完成后再启动下一个请求。

(如果你的URL在同一台服务器上,你可以考虑重构你的服务器端代码,这样一个URL就可以完成你现在多个URL所做的所有工作。)

也可以使用"$.when"。我在我的一个项目中使用过它。

阅读jQuery API指令:

当两个ajax请求都成功时,执行函数myFunc,或者myFailure(如果其中任何一个出现错误)。

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
  .then( myFunc, myFailure );