douzhong5902
douzhong5902
2018-02-02 10:27

getJSON的jQuery响应不会显示

this is my code, which works not perfectly yet:

function func1() {
       $('.lastStateText').html("<img src='images/Loading.gif' />").fadeIn('slow')
       $('.lastStateText').each(function() {
          lastState('xxx').then(result => 
             $( this ).fadeOut(500, function(){
                $( this ).text(result)
                alert(result)
             })
          )
       })
    }

    function lastState(parameter) { 
       return new Promise( done =>
          $.getJSON("myFile.php", {
             parameter: parameter
          }, function(result) {
                done(result); 
             }
          )
       )
    }

What happens here?

  1. I call func1
  2. This function will show a Loading.gif in each element with the class "lastStateText" with a fadIn effect
  3. A loop will go through all lastStateText elements, fadeOut it out and call each time the next function lastState with a parameter 'xxx'. 4 The lastState function will get the result of myFile.php and give it back to the func1.
  4. Now the func1 should set the result into the lastStateText element <- but this doesn't work. now result will shown in the element. I checked with alert(result) if the result will be available and yes -> the result is there. but not visible in my lastStateText element.

Where is my fault?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongpao5658 dongpao5658 3年前

    I am assuming you have to support old(ish) browsers since you do not use arrow functions or native promises and do not use transpilers.

    The traditional way of parallel promises could be using the jQuery.when method, that will make all the requests for you.

    It would look something like this:

    function func1() {
      $.when.apply(//jQuery version of Promise.all
        $,
        $('.lastStateText')
        .html("<img src='images/Loading.gif' />")
        .fadeIn('slow')
        .map(
          function(index,element){
            return lastState('xxx').then(function(result) {
              $element = $(element);
              $element.fadeOut(500, function(){
                $element.text(result);
                $element.fadeIn(500);
                console.log("result",result);//changed to console.log
              })
            })
          }
        )
      ).then(
        function(){console.log("finished");}
      ).catch(
        function(){console.warn("something went wrong:",err);}
      );
    }
    function lastState(parameter) { 
        return $.getJSON(//getJSON already returns a promise like
          "myFile.php", 
          {
              parameter: parameter
          }
        );
    }
    
    点赞 评论 复制链接分享

相关推荐