Home > Web Front-end > JS Tutorial > How jQuery implements file download count statistics

How jQuery implements file download count statistics

php中世界最好的语言
Release: 2018-04-23 13:40:52
Original
5436 people have browsed it

This time I will show you how jQuery implements file download count statistics. What are the precautions for jQuery to implement file download count statistics? Here is a practical case, let’s take a look.

In the project, we need to count the number of file downloads. Every time a user downloads a file, the corresponding number of downloads increases by 1. Similar applications are used in many download sites. This article uses PHP Mysql jQuery based on examples to realize the process of clicking files, downloading files, and accumulating times. The whole process is very smooth.

Preparation workThis example requires readers to have basic knowledge of PHP, Mysql, jQuery, html, css, etc. Before developing the example, you need to prepare a Mysql data table. This article assumes that there is a file download table downloads, which is used to record the file name, the file name saved on the file server, and the number of downloads. The premise is that there is already data in the download table. This data may be inserted from the background upload file in the project so that we can read it in the page. The structure of the downloads table is as follows:

CREATE TABLE IF NOT EXISTS `downloads` ( 
 `id` int(6) unsigned NOT NULL AUTO_INCREMENT, 
 `filename` varchar(50) NOT NULL, 
 `savename` varchar(50) NOT NULL, 
 `downloads` int(10) unsigned NOT NULL DEFAULT '1', 
 PRIMARY KEY (`id`), 
 UNIQUE KEY `filename` (`filename`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Copy after login

You can also download the Demo directly, import the SQL file, and the data will be there.
HTMLWe add the following HTML structure to the index.html page body, in which ul.filelist is used to display the file list. Now it has no content. We will use jQuery to read the file list asynchronously. So don't forget, we also need to load the jQuery library file in html.

<p id="demo"> 
  <ul class="filelist"> 
  </ul> 
</p>
Copy after login

CSS
In order to make the demo better display the page effect, we use CSS to modify the page. The following code mainly sets the file list display effect. Of course, in the actual project, it can be based on The corresponding styles need to be set.

#demo{width:728px;margin:50px auto;padding:10px;border:1px solid #ddd;background-color:#eee;} 
ul.filelist li{background:url("img/bg_gradient.gif") repeat-x center bottom #F5F5F5; 
border:1px solid #ddd;border-top-color:#fff;list-style:none;position:relative;} 
ul.filelist li.load{background:url("img/ajax_load.gif") no-repeat; padding-left:20px; 
border:none; position:relative; left:150px; top:30px; width:200px} 
ul.filelist li a{display:block;padding:8px;} 
ul.filelist li a:hover .download{display:block;} 
span.download{background-color:#64b126;border:1px solid #4e9416;color:white; 
display:none;font-size:12px;padding:2px 4px;position:absolute;right:8px; 
text-decoration:none;text-shadow:0 0 1px #315d0d;top:6px; 
-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;} 
span.downcount{color:#999;padding:5px;position:absolute; margin-left:10px;text-decoration:none;}
Copy after login

PHPFor better understanding, we divide into two PHP files, one is filelist.php, which is used to read the data in the mysql data table and output it in JSON format The data is used to call the front-end index.html page, and the other is download.php, which is used to respond to the download action, update the number of downloads of the corresponding file, and complete the download through the browser. filelist.php reads the downloads table and outputs the data in JSON format through json_encode(), which is prepared for the following Ajax asynchronous operation.

require 'conn.php'; //连接数据库 
$result = mysql_query("SELECT * FROM downloads"); 
if(mysql_num_rows($result)){ 
  while($row=mysql_fetch_assoc($result)){ 
    $data[] = array( 
      'id' => $row['id'], 
      'file' => $row['filename'], 
      'downloads'=> $row['downloads'] 
    ); 
  } 
  echo json_encode($data); 
}
Copy after login

download.php passes parameters according to the url, queries to obtain the corresponding data, detects whether the file to be downloaded exists, and if it exists, updates the number of downloads of the corresponding data to 1, and uses header() to implement the download function. It is worth mentioning that the header() function is used to force the file to be downloaded, and the file name can be set to be saved locally after downloading. Under normal circumstances, we use the background upload program to rename the uploaded files and save them to the server. Commonly used files are named after date and time. One of the benefits of this is that it avoids duplication of file names and garbled Chinese names. For files we download locally, we can use header("Content-Disposition: attachment; filename=" .$filename) to set the file name to an easily identifiable file name.

require('conn.php');//连接数据库 
$id = (int)$_GET['id']; 
 
if(!isset($id) || $id==0) die('参数错误!'); 
$query = mysql_query("select * from downloads where id='$id'"); 
$row = mysql_fetch_array($query); 
if(!$row) exit; 
$filename = iconv('UTF-8','GBK',$row['filename']);//中文名称注意转换编码 
$savename = $row['savename']; //实际在服务器上的保存名称 
$myfile = 'file/'.$savename; 
if(file_exists($myfile)){//如果文件存在 
  //更新下载次数 
  mysql_query("update downloads set downloads=downloads+1 where id='$id'"); 
  //下载文件 
  $file = @ fopen($myfile, "r"); 
  header("Content-type: application/octet-stream"); 
  header("Content-Disposition: attachment; filename=" .$filename ); 
  while (!feof($file)) { 
    echo fread($file, 50000); 
  } 
  fclose($file); 
  exit; 
}else{ 
  echo '文件不存在!'; 
}
Copy after login

jQuery
JQuery on the front-end page mainly completes two tasks. One is to read the file list asynchronously through Ajax and display it, and the other is to respond to the user's click event and download the corresponding file. Times 1, look at the code:

$(function(){ 
  $.ajax({ //异步请求 
    type: 'GET', 
    url: 'filelist.php', 
    dataType: 'json', 
    cache: false, 
    beforeSend: function(){ 
      $(".filelist").html("<li class=&#39;load&#39;>正在载入...</li>"); 
    }, 
    success: function(json){ 
      if(json){ 
        var li = ''; 
        $.each(json,function(index,array){ 
          li = li + '<li><a href="download.php?id=&#39;+array[&#39;id&#39;]+&#39;">'+array['file']+ 
'<span class="downcount" title="下载次数">'+array['downloads']+'</span> 
<span class="download">点击下载</span></a></li>'; 
        }); 
        $(".filelist").html(li); 
      } 
    } 
  }); 
  $('ul.filelist a').live('click',function(){ 
    var count = $('.downcount',this); 
    count.text( parseInt(count.text())+1); //下载次数+1 
  }); 
});
Copy after login

First, after the page is loaded, an Ajax request in the form of GET is sent to the background filelist.php through $.ajax(). When filelist.php responds successfully, receive The returned json data traverses the json data object through $.each(), constructs the html string, and adds the final string to ul.filelist to form the file list in the demo.
Then, when the file is clicked to download, the click event of the dynamically added list element is responded to through live(), and the number of downloads is accumulated.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Using jquery plug-in ajaxupload for file upload

##jQuery plug-in Tocify dynamic node implementation directory menu

The above is the detailed content of How jQuery implements file download count statistics. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template