如何随机化我的JSON响应?

时间:2018-02-02 15:19:25

标签: javascript json ajax

我收到了我对我正在使用的API的GET请求的回复,这很好。每次点击我的按钮时,我只需要随机响应,但我遇到了麻烦。我的代码中有一个math.random函数,但我现在还没有激活,因为我不知道如何处理它。我尝试了一些不同的方法,但似乎没有任何效果。

$(document).ready(function(){


    //When you click the submit button it fires off the getRequest.
    $(function(){
      $('#search-term').submit(function(e){
         e.preventDefault();
            myFunction();
            //clearText();
      });
    });



    // This is the get request. I want it to have a random function that randomizes the callback data. Once you get the randomizes data, it shows in the console window. I want this function display three random results based on the myFunction() below
    function getRequest(){
      $.ajax({
        url:'https://api.foursquare.com/v2/venues/search? ll=40.7,-74&client_id={my client id]&client_secret=[my secret]',
        type: 'GET',
        dataType:'json',
        success: function(data){
          var venues = data['response']['venues'];

          //This is my random function which I do not know what to do with
          var random = [Math.floor(Math.random() * venues.length)];

           $.each(venues, function(key,index){
             console.log(index.name);
             $('#search-results').append(index.name + '<br>');
           })
         }
       })
     };



    //This is the function that calls getRequest function three times then stops.
    function myFunction(){
        var myVar = setInterval(function(){getRequest();}, 500);
        //clearTimeout(myVar);
        setTimeout(function( ) { clearInterval( myVar); }, 1600);
    }


    //This function clears the text that exists in the form so that the new random text can populate it.
    function clearText(){
      $("#search-results").text("");
    };
});

0 个答案:

没有答案