开发者

JQuery getJSon nested calls not working

I need to perform two AJAX calls through JQuery's getJSON function.

The thing is that, once one of the calls is performed I need to immediately call the second getJSON function (because I need the result of the first call as a parameter in the second call).

My code looks like this:开发者_如何学运维

$.getJSON("/Traslados/ObtenerCedulas", { Param1: $("#Param1").val(), Param2: $("#Param2").val() }, function (j) {
      $("#Result1").val(j); 
      $.getJSON("/Traslados/ObtenerLogins", { Param3: $("#Param3").val(), Param4: $("#Result1").val() },  
                function (k) {
                        alert(k);
                        $("#Result2").val(k);
       });
 });

The problem is, although the second call is being performed correctly and is given the expected result (I debugged this using Firebug's console), it doesn't trigger the alert and even worst, it doesnt set the k value to my Result2 input field.

What's happening?


One thing I can see as a problem here is that your second getJSON call is happening whether the first call succeeds or fails and from the code you've posted there's no way to know whether #Result1 was actually set correctly.

If you look at the getJSON API doc: http://api.jquery.com/jQuery.getJSON/ It will show you how to structure your 1st getJSON so that you have some done/failure/always kinds of response handlings.

If memory serves, this is not your whole problem, though. When I've needed to do ajax calls that must happen in order, in the past, I've used queuing and dequeing my calls.

A quick example of queuing

<html>
<header>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script>
  function fakey_not_ajax(message, callback) {
    alert (message);
    callback();
  }
  function queue_my_stuff( kick_it_off_callback ) {
    $(document).queue("mydemo_queue", function(){
      fakey_not_ajax("show me first", function() { 
        $(document).dequeue("mydemo_queue");
      });
    });
    $(document).queue("mydemo_queue", function(){
      fakey_not_ajax("show me second", function() { 
        $(document).dequeue("mydemo_queue");
      });
    });

    kick_it_off_callback();
  }
  function push_the_button() {
    alert ("pushed");
    queue_my_stuff(
      function(){ 
        $(document).dequeue("mydemo_queue");
      }
    );
  }
</script>
</header>
<body>
Try this
<a href="#" onclick="push_the_button();">Push Me</a>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜