如何在api每秒更改数据的同时将来自API的数据存储在ajax变量中?

时间:2018-09-20 16:21:44

标签: jquery ajax

我已经在具有JSON格式数据的实时 RESTful API 上创建了ajax。每秒钟数据值已更改。

如果数据值当前值大于倒数第二个值,如何更改背景褪色?

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

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>
                                 

1 个答案:

答案 0 :(得分: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 }

作为摘要的示例:

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/