search
HomeWeb Front-endJS TutorialHow jQuery implements file download count statistics
How jQuery implements file download count statisticsApr 23, 2018 pm 01:40 PM
jqueryDownload Documentfrequency

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;

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> 
  </p>
        
 

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;}

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); 
}

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 '文件不存在!'; 
}

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("
  • 正在载入...
  • ");      },      success: function(json){        if(json){          var li = '';          $.each(json,function(index,array){            li = li + '
  • '+array['file']+  ''+array['downloads']+'  点击下载
  • ';          });          $(".filelist").html(li);        }      }    });    $('ul.filelist a').live('click',function(){      var count = $('.downcount',this);      count.text( parseInt(count.text())+1); //下载次数+1    });  });

    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!

    Statement
    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
    jquery实现多少秒后隐藏图片jquery实现多少秒后隐藏图片Apr 20, 2022 pm 05:33 PM

    实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

    jquery怎么修改min-height样式jquery怎么修改min-height样式Apr 20, 2022 pm 12:19 PM

    修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

    axios与jquery的区别是什么axios与jquery的区别是什么Apr 20, 2022 pm 06:18 PM

    区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

    jquery怎么在body中增加元素jquery怎么在body中增加元素Apr 22, 2022 am 11:13 AM

    增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

    jquery中apply()方法怎么用jquery中apply()方法怎么用Apr 24, 2022 pm 05:35 PM

    在jquery中,apply()方法用于改变this指向,使用另一个对象替换当前对象,是应用某一对象的一个方法,语法为“apply(thisobj,[argarray])”;参数argarray表示的是以数组的形式进行传递。

    jquery怎么删除div内所有子元素jquery怎么删除div内所有子元素Apr 21, 2022 pm 07:08 PM

    删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

    jquery怎么去掉只读属性jquery怎么去掉只读属性Apr 20, 2022 pm 07:55 PM

    去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

    jquery on()有几个参数jquery on()有几个参数Apr 21, 2022 am 11:29 AM

    on()方法有4个参数:1、第一个参数不可省略,规定要从被选元素添加的一个或多个事件或命名空间;2、第二个参数可省略,规定元素的事件处理程序;3、第三个参数可省略,规定传递到函数的额外数据;4、第四个参数可省略,规定当事件发生时运行的函数。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!