Ajax从控制器中以“正在加载"消息加载数据 [英] Ajax loading data from controller in view with 'loading' message

查看:52
本文介绍了Ajax从控制器中以“正在加载"消息加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Now I'm loading data from cURL in my controller and showing it in my view file but loading from cURL take long time so my webiste is loading very long too.

我想创建加载效果,只需使用正在加载,请稍候"加载我的所有页面.直到cURL数据可用,然后隐藏加载消息并显示我的数据.

I want to create loading effect, just load all of my page with "Loading, please wait." message untill cURL data will be available, and after it hide loading message and show my data.

我应该怎么做?

我的代码:

控制器:

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'].

$items in view is $json['data'] in controller.

查看:

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

致谢.

推荐答案

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

One approach that you can apply is using Ajax.

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

AJAX is an abbreviation standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh. In your case once the javascript ajax file is loaded, you send an Ajax call to the route that you have your controller in. In your controller you can return data in JSON ,XML,HTML ,... and in success call back function(a function to be called if the request succeeds) you will get your data from server as first parameter then you can hide your waiting and append data you get to DOM element.
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/

Here is an example you may find helpful to understand http://jsfiddle.net/tg5op333/21/

这篇关于Ajax从控制器中以“正在加载"消息加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆