Multiple url in same ajax call?is this possible?

后端 未结 4 1022
忘了有多久
忘了有多久 2020-12-01 11:16

Can I send my data to multiple pages using ajax call? I dont want to use another ajax call for this.

Sample code:

 $.ajax({
     type: \'POST\',
             


        
相关标签:
4条回答
  • 2020-12-01 11:49

    Using '$.when' could be an alternative as well. I have used it in one of my project.

    Reading jQuery API instructions:

    Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.

    $.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
      .then( myFunc, myFailure );
    
    0 讨论(0)
  • 2020-12-01 11:57

    All you need is $.each and the two parameter form of $.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);
             } 
           }
         );
    });
    

    Note: The messages generated by the success callback will overwrite each other as shown. You'll probably want to use $('#someDiv').append() or similar in the success function.

    0 讨论(0)
  • 2020-12-01 11:57

    A single AJAX request can only talk to one URL, but you can create multiple AJAX requests for different URLs, and they will do their work simultaneously - you wouldn't need to wait for one to complete before firing off the next one.

    (If your URLs are on the same server, you could consider refactoring your server-side code so that a single URL does all the work that your multiple URLs do now.)

    0 讨论(0)
  • 2020-12-01 12:00

    You can't use the same code for 1 request from many pages.

    BUT you can send 2 requests. its can be done by copy paste your ajax code or by build a function that gets URL and send request with this 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);
             }
         });
    };
    
    0 讨论(0)
提交回复
热议问题