【问题标题】:How can I store data from API in ajax variable while api changing data each sec?如何在 api 每秒更改数据时将来自 API 的数据存储在 ajax 变量中?
【发布时间】:2018-12-29 19:40:54
【问题描述】:

我在具有 JSON 格式数据的实时 RESTful API 上创建了 ajax。每一秒。数据值发生变化。

如果数据值当前值大于上一秒值,如何更改背景颜色渐变?

在这里,我的 ajax 代码与 API 世界市场:

setInterval(function(){
        $.ajax({
            type:"get",
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
            url:"http://www.yourtradelog.com/liveapi/world-markets",
            data:{"_token": "{{ csrf_token() }}"},
            dataType:'json',
            success:function(res){
                if(!res){
                    alert('Something went wrong')
                }else{
                    $('#sensex').text(res.sensex.lastprice);

                    if(res.sensex.lastprice > 0){
                        console.log("green");
                        document.getElementById("chg").className = "greenText";
                    }
                    else{
                        document.getElementById("chg").className = "redText";
                    }
                }
            }
        });
    },1000);
div {
        transition: background 0.5s linear;
    }

    .greenText {
        background-color: rgb(83, 241, 83);
    }
    .redText {
        background-color: red;
    }
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
    <div id="chg">Test</div>
    
     
                                     <a id="sensex" ></a>
                                 

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    效果可以通过CSS和transition动画实现

    过渡使您能够定义元素的两种状态之间的过渡。可以使用 :hover 或 :active 等伪类定义不同的状态,也可以使用 JavaScript 动态设置。

    setInterval(function() {
      document.body.className = (document.body.className === "flash" ? "" : "flash");
    }, 2000);
    body { transition: background 0.5s linear; }
    .flash { background-color: yellow; }

    现在我们需要一种方法来检测当前值是否大于前一个值。为此,我们可以使用.data() 来存储当前值,即下一轮的“旧”值。

    (或多或少的伪代码)

    var output = $("#sensex"),
        oldValue = output.data("oldValue") || 0;
        // get the "old" value or zero if there hasn't been an "old" value yet
    
    /*...*/
    
    output.data("oldValue", res.sensex.lastprice);
    // store the current value in "oldValue" for the next round
    
    /*...*/
    
    if (res.sensex.lastprice > oldValue) {
      // change background color
    }
    

    如果我们将这两个步骤结合起来,我们会为 success 处理程序提供类似的内容:

    var output = $("#sensex"),
        oldValue = output.data("oldValue") || 0;
    
    output[0].className = "";
    
    output.text(res.sensex.lastprice)
          .data("oldValue", res.sensex.lastprice)
          .addClass(res.sensex.lastprice > 0 ? "greenText" : "redText");
    
    if (res.sensex.lastprice > oldValue) {
        output.addClass("flash");
    }
    

    这对于 CSS (简化示例)

    #chg { transition: background 0.5s linear }
    .flash { background-color: yellow }
    .greenText { color: green }
    .redText { color: red }
    

    sn-p 示例:

    setInterval(function() {
      getNewValue()
        .then(function(res) {
            var output = $("#sensex"),
                oldValue = output.data("oldValue") || 0;
    
            output[0].className = "";
    
            output.text(res.sensex.lastprice)
                  .data("oldValue", res.sensex.lastprice)
                  .addClass(res.sensex.lastprice > 0 ? "greenText" : "redText");
    
            if (res.sensex.lastprice > oldValue) {
              output.addClass("flash");
            }
        });
    }, 2000);
    
    
    /* fake api call */
    function getNewValue() {
      return $.Deferred().resolve({
        sensex: {
            lastprice: Math.floor(Math.random() * 100) * (Math.random() > .5 ? 1 : -1)
        }
      }).promise();
    }
    #sensex { transition: background 0.5s linear }
    .flash { background-color: yellow }
    .greenText { color: green }
    .redText { color: red }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="sensex"></div>

    jsfiddle 示例:http://jsfiddle.net/h8k1ar5z/

    【讨论】:

    • 我应该不需要存储变量最后一秒的值吗?....如何理解我的代码当前第二个值大于最后一秒?
    • @KINNARI 我已经修改了我的答案
    • 好的,让我试试你的答案。感谢先进的@Andreas
    • 错误:Uncaught TypeError: Cannot read property 'dataset' of null
    • 即使您对代码进行了所有更改,也只有在没有 ID 为 chg 的元素时才会出现此错误
    猜你喜欢
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 2019-03-05
    • 2017-02-05
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多