Ajax从视图中的控制器加载数据,带有'loading'消息

时间:2016-03-30 01:12:57

标签: php jquery json ajax curl

现在我正在我的控制器中从cURL加载数据并在我的视图文件中显示它,但是从cURL加载需要很长时间,因此我的网站加载时间也很长。

我想创建加载效果,只需加载我的所有页面“加载,请稍候”。消息,直到cURL数据可用,并在隐藏加载消息并显示我的数据之后。

我该怎么做?

我的代码:

控制器:

public function open_inventory($steam_id, $appid = 730, $contextid = 2)
{
    $data = array("steamid" => $steam_id, "appid" => $appid);

    $cache_file = $this->config->item('inv_dir')."/".$data['steamid']."_".$data['appid'].".json";

    if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 60 ))) // 1 hour cache
    {
       $output = file_get_contents($cache_file);
    }
    else
    {
        // out-of-date
        $data_string = json_encode($data);                                                                                   

        $ch = curl_init('http://localhost:3000');                                                                      
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string))
        );
        $output = curl_exec($ch);

        file_put_contents($cache_file, $output, LOCK_EX);
    }

    $json = json_decode($output,true);

    if($json['data'])
    {
        return $json;
    }

    return false;
}

$items在控制器中是$json['data']

查看:

<?php foreach ($items as $item): ?>
    <div class="item-slot animated zoomIn" data-id="<?= $item['id'] ?>
        <p><?= $item['name'] ?></p>
    </div>
<?php endforeach; ?>

问候。

1 个答案:

答案 0 :(得分:0)

您可以应用的一种方法是使用 Ajax

AJAX 异步JavaScript和XML 的缩写,此技术可帮助我们在不刷新浏览器页面的情况下从服务器加载数据。在您的情况下,一旦加载了javascript ajax文件,您就会向您的控制器所在的路由发送Ajax调用。在您的控制器中,您可以使用JSON,XML,HTML,...以及成功回调函数返回数据(如果请求成功则调用的函数)您将从服务器获取数据作为第一个参数,然后您可以隐藏等待并附加到DOM元素的数据。
HTML:

<div id="wait-container">
  Please wait....
  <div class="spinner">
  </div> 
</div>
<div id="items"></div>

JS:

$(function(){
     // data that you can send to the server 
     var data = {key1 :'value1',key2:'value2'} ;
     console.log("Data :",data);


      $.ajax({ url: '/path_to_your_php_controller', //replace your url
                data: data ,
                type: 'post',
                dataType: "json",
                success: function(response) {
                    //here hide wait-container
                     $("#wait-container").hide();
                     console.log(response);
                     var string = '';
                     $.map( response, function( val) {
                        // Generate Html
                        string += "<div class='item-slot animated zoomIn' data-id='" + val.id + "'><p>" + val.name + "</p></div>";
                     });
                      //add generated Html to the element.
                      $("#items").html(string);

                },
                error: function(jqXHR, exception) {
                    if (jqXHR.status === 0) {
                        alert('Not connect.\n Verify Network.');
                    } else if (jqXHR.status == 404) {
                        alert('Requested page not found. [404]');
                    } else if (jqXHR.status == 500) {
                        alert('Internal Server Error [500].');
                    } else if (exception === 'parsererror') {
                        alert('Requested JSON parse failed.');
                    } else if (exception === 'timeout') {
                        alert('Time out error.');
                    } else if (exception === 'abort') {
                        alert('Ajax request aborted.');
                    } else {
                        alert('Uncaught Error.\n' + jqXHR.responseText);
                    }
                }
        });
})
$(document).on("click",".item-slot",function() {
    alert($(this).data('id'));
});

PHP:

 <?php
    public function open_inventory()
    {
       // your code here 

       // array of object 
        $arr = array ({'id'=>123,'name'=>'name 1'},{'id'=>2345,'name'=>'name 2'},{'id'=>3423,'name'=>'name 3'},);

       echo json_encode($arr); 
    }

?>

以下是您可能会发现有助于理解http://jsfiddle.net/tg5op333/21/

的示例