weixin_33691598 2015-11-29 06:20 采纳率: 0%
浏览 24

AJAX多个Ajax调用

I have the below code and it is acting in a way that I dont understand. The purpose seems pretty straightforward to me, if the first ajax call is successful, then get the loggedInUser from another ajax GET call and reload the page to the link created. My Code looks like

function getLoggedInUser() {    
  var username = "";    
  $.ajax({
    url: '/api/getLoggedInUser',
    data: [],
    dataType: 'json',
    type: 'GET',
    success: function(response) {
      alert("a " + username);
      username = response.username;
      alert("b " +username);
      var link = "/_marshall/rssadd/";
      link = link+username;
      alert("c " + link);

    },
    error: function(xhr, status, error) {
    var err = eval("(" + xhr.responseText + ")");
    //alert("Please Try Again, we had an internal error!");
      alert(err.message);
      args['error'] = "1";
    }
  });

  alert("d " + username);
  return username;
}

$(document).ready(function ()
{    
  $("#rssCreateSubmit").click(function(event) {    
    var rssInfo = {}    
    rssInfo["title"] = $("#rssCreateTitle").val();
    rssInfo["category"] = $("#rssCreateCategory").val();
    rssInfo["copyright"] = $("#rssCreateCopyright").val();
    rssInfo["description"] = $("#rssCreateDescription").val();

    $.ajax({
      url: '/api/createRSS',
      data: rssInfo,
      dataType: 'json',
      type: 'POST',
      success: function(response)
      {
        var loggedInUser = getLoggedInUser();
        alert("e " + loggedInUser);
      },
      error: function(xhr, status, error)
      {
      var err = eval("(" + xhr.responseText + ")");
      //alert("Please Try Again, we had an internal error!");
      alert(err.message);
      }
    });
  });

});

The alerts print out in this order, which I do not understand. I think it has something to do with ajax being asynchronous, but I am not too sure what that means and I still feel like this code should work. Thanks.

"d "
"e "
"a "
"b value"
"c /_marshall/rssadd/value"

And the html link in changes to the below instead of rerouting:

http://www.bugbounty.design/_marshall/rsscreate/testMarshall1?rssCreateCategory=&InputEmail=
  • 写回答

2条回答 默认 最新

  • 衫裤跑路 2015-11-29 06:30
    关注

    Ajax calls are taken out of the main execution thread. This is why 'd' and 'e' are printed first, since they are not in an ajax call.

    I found this video really helpful for understanding ajax https://www.youtube.com/watch?v=8aGhZQkoFbQ

    评论

报告相同问题?