代码之家  ›  专栏  ›  技术社区  ›  Lukas Naujokaitis

由于折旧,转换为ajax异步错误替代方案

  •  1
  • Lukas Naujokaitis  · 技术社区  · 8 年前

    我对这个问题进行了研究,并找到了一些解决方案。然而,并不是每一个都有效。据我所知,async false会生成一个UI块,这是不应该的。我可以使用覆盖,直到ajax请求完成,如果请求成功,则隐藏覆盖。

    这是我尝试在 getNewQuote() 函数(仅一小部分):

    var getNewQuote = function(callback) {
      var quote = {};
      setTimeout(function() {
        quote.text = 'Example';
        quote.author = 'Example';
        callback();
        return quote;
      }, 4000);
    };
    
    getNewQuote(function() {
      console.log("DONE");
      var getRandomColor = function() {
      var colors = [
          "#ff9966",
          "#7f00ff",
          "#396afc",
          "#0cebeb",
          "#06beb6",
          "#642b73",
          "#36d1dc",
          "#cb356b",
          "#3a1c71",
          "#ef3b36",
          "#159957",
          "#000046",
          "#007991",
          "#56ccf2",
          "#f2994a",
          "#e44d26",
          "#4ac29a",
          "#f7971e",
          "#34e89e",
          "#6190e8",
          "#3494e6",
          "#ee0979"
        ],
        randomNumber = Math.floor(Math.random() * colors.length);
      return colors[randomNumber];
    };
    
    var updateText = function($t, qt) {
    
      var twitter = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
      twitter += '"' + qt.text + '" ';
      twitter += qt.author;
    
      var tumblr = "https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=";
      tumblr += qt.author;
      tumblr += "&content=";
      tumblr += qt.text;
      tumblr += "&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button";
    
      var $icon = $("<i class='fa fa-quote-left'>")
        .prop("aria-hidden", true);
    
      $t.find(".quote-text").html("").append($icon, qt.text);
      $t.find(".quote-author").html("- " + qt.author);
      $("#tweet-quote").attr("href", twitter);
      $("#tumblr-quote").attr("href", tumblr);
    };
    
    var calcNewHeight = function(q) {
      var $temp = $("<div>", {
        class: "quote-container temp",
      }).appendTo($("body"));
      $temp.append($("<div>", {
        class: "quote-text"
      }), $("<div>", {
        class: "quote-author"
      }));
      updateText($temp, q);
      var h = $temp.height() + 40;
      $temp.remove();
      return h;
    };
    
    var changeColor = function(newColor) {
      $("body, .button:not(#new-quote)").animate({
        backgroundColor: newColor
      });
      $("#new-quote").animate({
        color: newColor
      });
      $(".quote-text, .quote-author").css("color", newColor);
      if ($("#modStyle").length === 0) {
        $("head").append(
          "<style id='modStyle'>#new-quote:before {background:" + newColor + ";}</style>"
        );
      } else {
        $("head style#modStyle").html("#new-quote:before {background:" + newColor + ";}");
    
      }
    };
    
    var getQuote = function() {
      var nq, nc, nh = 0;
    
          nq = getNewQuote();
          nc = getRandomColor();
          nh = calcNewHeight(nq);
      
          $(".quote-container").children().css("opacity", 0);
          changeColor(nc);
      
          $(".quote-container, #new-quote").animate({
            height: nh,
          }, {
            duration: 1000,
            queue: false
          });
    
          $(".quote-container").animate({
            padding: "2.5em"
          }, {
            duration: 1000,
            queue: false
          });
    
          $("#new-quote").animate({
            padding: "2.5em .75em"
          }, {
            duration: 1000,
            queue: false
          });
      
          updateText($(".quote-container"), nq);
          $(".quote-container").children().fadeTo(750, 1);
    };
    
      $("#new-quote").on("click", getQuote);
      $(".quote-container, #new-quote").css({
        visibility: "visible",
        height: 0
      });
      $("#new-quote").css("padding", "0 .75em");
      getQuote();
    });
    html,
    body {
      height: 100%;
      width: 100%;
    }
    
    body {
      margin: 0;
      padding: 0;
      background: #333;
      color: #333;
      font-family: sans-serif;
    }
    
    .v-wrap {
      height: 100%;
      text-align: center;
    }
    
    .v-wrap:before {
      content: "";
      display: inline-block;
      vertical-align: middle;
      width: 0;
      height: 100%;
    }
    
    .quote-container {
      width: 31.25rem;
      background: #fff;
      margin: 0;
      display: inline-block;
      vertical-align: middle;
      border-radius: 0.1875rem;
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
      visibility: hidden;
      padding: 0 2.5rem;
    }
    
    .quote-text {
      font-size: 1.625rem;
    }
    
    .quote-text i {
      margin-right: 0.6rem;
    }
    
    .quote-text p {
      display: inline;
    }
    
    .quote-author {
      font-size: 1rem;
      margin: 0 0.4rem 2rem 0;
      text-align: right;
    }
    
    .button {
      padding: 0.75rem;
      text-align: center;
      font-size: 1rem;
      color: #fff;
      border-radius: .1875rem;
      display: inline-block;
      cursor: pointer;
      -webkit-user-select: none;
      user-select: none;
    }
    
    .button:not(#new-quote):hover {
      opacity: .8 !important;
    }
    
    .button:not(#new-quote) {
      min-width: 1rem;
      min-height: 1rem;
    }
    
    .button i {
      vertical-align: middle;
    }
    
    #new-quote {
      white-space: nowrap;
      writing-mode: vertical-lr;
      height: 50%;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      vertical-align: middle;
      background: #fff !important;
      margin: 0;
      position: relative;
      right: 0.25625rem;
      color: #333;
      visibility: hidden;
    }
    
    #new-quote:before {
      content: "";
      position: absolute;
      height: 100%;
      width: 0.0625rem;
      bottom: 0;
      left: 0;
      visibility: hidden;
      -webkit-transform: scaleY(0);
      transform: scaleY(0);
      -webkit-transition: all .3s ease-in-out;
      transition: all .3s ease-in-out;
    }
    
    #new-quote:hover:before {
      visibility: visible;
      -webkit-transform: scaleY(1);
      transform: scaleY(1);
    }
    
    footer {
      font-size: 0.85rem;
      margin-bottom: 1rem;
    }
    
    footer a {
      text-decoration: none;
      color: #fff;
      position: relative;
    }
    
    footer a:before {
      content: "";
      position: absolute;
      width: 100%;
      height: .0625rem;
      bottom: 0;
      left: 0;
      background: #fff;
      visibility: hidden;
      -webkit-transform: scaleX(0);
      transform: scaleX(0);
      -webkit-transition: all .3s ease-in-out 0s;
      transition: all .3s ease-in-out 0s;
    }
    
    footer a:hover:before {
      visibility: visible;
      -webkit-transform: scaleX(1);
      transform: scaleX(1);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="v-wrap">
      <div class="quote-container" style="">
        <div class="quote-text">
        </div>
        <div class="quote-author"></div>
        <a id="tweet-quote" class="button"><i class="fa fa-twitter"></i></a>
        <a id="tumblr-quote" class="button"><i class="fa fa-tumblr"></i></a>
      </div>
      <div id="new-quote" class="button">New quote</div>
      <footer>
        <a href="https://codepen.io/Kestis500">Created by LukasLSC</a>
      </footer>
    </div>

    代码输出: enter image description here 正如您所看到的,ajax没有成功

    Uncaught TypeError:回调不是函数,Uncaught TypeError:无法读取未定义的属性“text”(仅在堆栈片段中)。

    我发现如果删除 getQuote(); 函数调用。然而,我需要称之为“过度疲劳”,我的项目无法工作。我也试着使用 return $.ajax 但是有一个 return quote 所以我无法使用它。完整代码可在codepen上找到: https://codepen.io/Kestis500/pen/ZvyxKB?editors=0110 .


    然后,我切换到使用jQuery承诺的另一种方法,并在此线程中使用了信息: https://stackoverflow.com/a/40658281/8889739 . 完整代码: https://codepen.io/Kestis500/pen/qpjxoq?editors=0110 .

    var MyFirstFunction = function() {
      var getNewQuote = function(callback) {
        var quote = {};
        setTimeout(function() {
          quote.text = 'Example';
          quote.author = 'Example';
    
          return quote;
        }, 4000);
      };
    }
    
    var MySecondFunction = function() {
      console.log("DONE");
      var getRandomColor = function() {
        var colors = [
            "#ff9966",
            "#7f00ff",
            "#396afc",
            "#0cebeb",
            "#06beb6",
            "#642b73",
            "#36d1dc",
            "#cb356b",
            "#3a1c71",
            "#ef3b36",
            "#159957",
            "#000046",
            "#007991",
            "#56ccf2",
            "#f2994a",
            "#e44d26",
            "#4ac29a",
            "#f7971e",
            "#34e89e",
            "#6190e8",
            "#3494e6",
            "#ee0979"
          ],
          randomNumber = Math.floor(Math.random() * colors.length);
        return colors[randomNumber];
      };
    
      var updateText = function($t, qt) {
    
        var twitter = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
        twitter += '"' + qt.text + '" ';
        twitter += qt.author;
    
        var tumblr = "https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=";
        tumblr += qt.author;
        tumblr += "&content=";
        tumblr += qt.text;
        tumblr += "&canonicalUrl=https%3A%2F%2Fwww.tumblr.com%2Fbuttons&shareSource=tumblr_share_button";
    
        var $icon = $("<i class='fa fa-quote-left'>")
          .prop("aria-hidden", true);
    
        $t.find(".quote-text").html("").append($icon, qt.text);
        $t.find(".quote-author").html("- " + qt.author);
        $("#tweet-quote").attr("href", twitter);
        $("#tumblr-quote").attr("href", tumblr);
      };
    
      var calcNewHeight = function(q) {
        var $temp = $("<div>", {
          class: "quote-container temp",
        }).appendTo($("body"));
        $temp.append($("<div>", {
          class: "quote-text"
        }), $("<div>", {
          class: "quote-author"
        }));
        updateText($temp, q);
        var h = $temp.height() + 40;
        $temp.remove();
        return h;
      };
    
      var changeColor = function(newColor) {
        $("body, .button:not(#new-quote)").animate({
          backgroundColor: newColor
        });
        $("#new-quote").animate({
          color: newColor
        });
        $(".quote-text, .quote-author").css("color", newColor);
        if ($("#modStyle").length === 0) {
          $("head").append(
            "<style id='modStyle'>#new-quote:before {background:" + newColor + ";}</style>"
          );
        } else {
          $("head style#modStyle").html("#new-quote:before {background:" + newColor + ";}");
    
        }
      };
    
      var getQuote = function() {
        var nq, nc, nh = 0;
    
        nq = getNewQuote();
        nc = getRandomColor();
        nh = calcNewHeight(nq);
    
        $(".quote-container").children().css("opacity", 0);
        changeColor(nc);
    
        $(".quote-container, #new-quote").animate({
          height: nh,
        }, {
          duration: 1000,
          queue: false
        });
    
        $(".quote-container").animate({
          padding: "2.5em"
        }, {
          duration: 1000,
          queue: false
        });
    
        $("#new-quote").animate({
          padding: "2.5em .75em"
        }, {
          duration: 1000,
          queue: false
        });
    
        updateText($(".quote-container"), nq);
        $(".quote-container").children().fadeTo(750, 1);
      };
    
      $("#new-quote").on("click", getQuote);
      $(".quote-container, #new-quote").css({
        visibility: "visible",
        height: 0
      });
      $("#new-quote").css("padding", "0 .75em");
      getQuote();
    }
    
    MyFirstFunction().done(MySecondFunction);
    html,
    车身{
    身高:100%;
    宽度:100%;
    }
    
    车身{
    边距:0;
    填充:0;
    背景:#333;
    颜色:#333;
    字体系列:无衬线;
    }
    
    .v形缠绕{
    身高:100%;
    文本对齐:居中;
    }
    
    .v形缠绕:之前{
    内容:“”;
    显示:内联块;
    垂直对齐:中间对齐;
    宽度:0;
    身高:100%;
    }
    
    .报价容器{
    宽度:31.25rem;
    背景:#fff;
    边距:0;
    显示:内联块;
    垂直对齐:中间对齐;
    边界半径:0.1875rem;
    边框右上半径:0;
    边框右下半径:0;
    可见性:隐藏;
    填充:0 2.5rem;
    }
    
    .报价文本{
    字体大小:1.625rem;
    }
    
    .引用文本i{
    右边距:0.6rem;
    }
    
    .报价文本p{
    显示:内联;
    }
    
    .引用作者{
    字号:1rem;
    保证金:0.4rem 2rem 0;
    文本对齐:右对齐;
    }
    
    .按钮{
    填充:0.75rem;
    文本对齐:居中;
    字号:1rem;
    颜色:#fff;
    边框半径:。1875雷姆;
    显示:内联块;
    光标:指针;
    -webkit用户选择:无;
    用户选择:无;
    }
    
    .按钮:非(#新报价):悬停{
    不透明度:。8.重要的
    }
    
    .按钮:非(#新报价){
    最小宽度:1rem;
    最小高度:1rem;
    }
    
    .按钮i{
    垂直对齐:中间对齐;
    }
    
    #新报价单{
    空白:nowrap;
    写入方式:垂直lr;
    身高:50%;
    边框左上半径:0;
    边框左下半径:0;
    垂直对齐:中间对齐;
    背景:#fff!重要的
    边距:0;
    位置:相对;
    右:0.25625rem;
    颜色:#333;
    可见性:隐藏;
    }
    
    #新报价:之前{
    内容:“”;
    位置:绝对;
    身高:100%;
    宽度:0.0625rem;
    底部:0;
    左:0;
    可见性:隐藏;
    -webkit转换:scaleY(0);
    变换:scaleY(0);
    -webkit转换:全部。3s轻松输入输出;
    过渡:全部。3s轻松输入输出;
    }
    
    #新报价:悬停:之前{
    可见性:可见;
    -webkit转换:scaleY(1);
    变换:scaleY(1);
    }
    
    页脚{
    字体大小:0.85rem;
    边缘底部:1rem;
    }
    
    页脚a{
    文字装饰:无;
    颜色:#fff;
    位置:相对;
    }
    
    页脚a:之前{
    内容:“”;
    位置:绝对;
    宽度:100%;
    高度:。0625rem;
    底部:0;
    左:0;
    背景:#fff;
    可见性:隐藏;
    -webkit转换:scaleX(0);
    变换:scaleX(0);
    -webkit转换:全部。3s轻松输入输出0s;
    过渡:全部。3s轻松输入输出0s;
    }
    
    页脚a:悬停:之前{
    可见性:可见;
    -webkit转换:scaleX(1);
    变换:scaleX(1);
    }
    <脚本src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script>
    <div class=“v-wrap”>
    <div class=“quote container”style=”>
    <div class=“报价文本”>
    </div>
    <div class=“报价作者”></div>
    <a id=“tweet quote”class=“button”>&书信电报;i class=“fa fa twitter”></i></a>
    <a id=“tumblr quote”class=“button”>&书信电报;i class=“fa fa tumblr”></i></a>
    </div>
    <div id=“new quote”class=“button”>新报价(</div>
    <页脚(>);
    <a href=”https://codepen.io/Kestis500“>由LukasLSC创建</a>
    </页脚(>);
    </div>

    代码输出: enter image description here 它打破了一切,灰色屏幕是因为默认的代码笔背景

    未捕获的TypeError:无法读取未定义的属性“done”

    1 回复  |  直到 8 年前
        1
  •  1
  •   T.J. Crowder    8 年前

    您正在使用 return 来自异步操作的回调。这只是设置回调的返回值(在 setTimeout ,它不会设置函数的返回值。

    不能 从函数返回值,这就是为什么要添加回调。而是:

    var getNewQuote = function(callback) {
      var quote = {};
      setTimeout(function() {
        quote.text = 'Example';
        quote.author = 'Example';
        callback(quote); // <====
      }, 4000);
    };
    

    ...并使用回调的参数,例如:

    getNewQuote(function(quote) {
        // Use quote here...
    });
    

    现场示例:

    var getNewQuote = function(callback) {
      var quote = {};
      setTimeout(function() {
        quote.text = 'Example';
        quote.author = 'Example';
        callback(quote); // <====
      }, 1000);
    };
    
    getNewQuote(function(quote) {
        console.log("quote:", quote);
    });