Home > Backend Development > PHP Tutorial > The fourth day of php practical combat_PHP tutorial

The fourth day of php practical combat_PHP tutorial

WBOY
Release: 2016-07-14 10:10:50
Original
18627 people have browsed it

Okay, let’s take a look at the picture first. This is an ajax message board. It has a waterfall effect, haha


1. Today I learned jquery’s ajax and can directly code


[php] / JavaScript Document
$(document).ready(function(e) {
LoadHiglight();//Load highlight effects


$("#submit").click(function() { //"Message" button click event
//Get user name
        var strUsetName = $("#userName").val();
//Get the input message content
      var strContent = $("#content").val();
//Get input email address
      var strEmail = $("#email").val();

//Start sending data
         $.ajax({
​​​​​ url: 'index.php?m=index&a=add',
           type: 'POST',
             dataType: 'json',
data: {
                   userName: strUsetName,
content: strContent,
Email: strEmail
            },
Success: function(json, textStatus, xhr) {
If (json.state=='ok') {
                      alert('Operation prompt, message successful!');                                      //alert();                                             var data=json.data[0];
                       var strTag=createTag(data.userName,data.content,data.time);

                             $(strTag).prependTo('div #liuyan');

//$("Hello World!").prependTo("p");
                                                                                                                                                                  alert('Operation prompt, message failed! Error message:'+json.error);
                                                                                                                                                                                                                                                                      })
});
//Dynamic loading of messages
loadMore();
});

//Monitor scroll bar scrolling
$(window).scroll(function() {
// When scrolling to 100 pixels above the bottom, load new content
If ($(document).height() - $(this).scrollTop() - $(this).height() < 5) {
        loadMore();
};
});



fy = 0;
function loadMore() {
fy++;
//alert(fy);
$.getJSON("index.php?m=index&a=data&page=" + fy + "&rand=" + Math.random(), function(json) {

for (var i = 0; i <= json.length - 1; i++) {
                 //alert(json[i]['userName']); 
//content = '

' + json[i]['userName'] + '
' + json[i]['content'] + '
' + getLocalTime(json[i]['time']) + '
';  
            //content='
'  
            //alert(content);  
            $("div #liuyan").append(createTag(json[i]['userName'],json[i]['content'],json[i]['time'])); 
            loadHiglight(); 
        }; 
 
    }); 

 
function loadHiglight() {//为了ajax后重载特效  
    $user = $("div .user"); 
    $text = $("div .text"); 
 
    $("div .content").each(function(index) { 
        $(this).mousemove(function() { 
 
            $user.eq(index).css("color", "#0A8CD2"); 
 
            //  $user.eq(index).css("background","#FFE6AD");  
            //  $text.eq(index).css("background","#FFFDF6");  
 
        }).mouseout(function() { 
 
            $user.eq(index).css("color", "#000"); 
 
            //  $user.eq(index).css("background","#E6F0F9");  
            //  $text.eq(index).css("background","#F8FBFD");  
        }); 
    }); 

function createTag(usetName, content, time) { 
    var strTag = '
' + usetName + '
' + content + '
' + getLocalTime(time) + '
'; 
    return strTag; 

function getLocalTime(nS) { 
    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' '); 

// JavaScript Document
$(document).ready(function(e) {
 loadHiglight();//载入高亮特效


 $("#submit").click(function() { //“留言”按钮单击事件
  //获取用户名称
  var strUsetName = $("#userName").val();
  //获取输入留言内容
  var strContent = $("#content").val();
  //获取输入邮箱
  var strEmail = $("#email").val();

  //开始发送数据
  $.ajax({
   url: 'index.php?m=index&a=add',
   type: 'POST',
   dataType: 'json',
   data: {
    userName: strUsetName,
    content: strContent,
    email: strEmail
   },
   success: function(json, textStatus, xhr) {
    if (json.state=='ok') {
     alert('操作提示,留言成功!'); 
     //alert();
     var data=json.data[0];
     var strTag=createTag(data.userName,data.content,data.time);

     $(strTag).prependTo('div #liuyan');

      //$("Hello World!").prependTo("p");
    }else{
     alert('操作提示,留言失败!\n错误信息:'+json.error); 
    }
   }
  })
 });
 //动态载入留言
 loadMore();
});

//监视滚动条滚动
$(window).scroll(function() {
 // 当滚动到最底部以上100像素时, 加载新内容
 if ($(document).height() - $(this).scrollTop() - $(this).height() < 5) {
  loadMore();
 };
});

 

fy = 0;
function loadMore() {
 fy++;
 //alert(fy);
 $.getJSON("index.php?m=index&a=data&page=" + fy + "&rand=" + Math.random(), function(json) {

  for (var i = 0; i <= json.length - 1; i++) {
   //alert(json[i]['userName']);
   //content = '

' + json[i]['userName'] + '
' + json[i]['content'] + '
' + getLocalTime(json[i]['time']) + '
';
   //content='
'
   //alert(content);
   $("div #liuyan").append(createTag(json[i]['userName'],json[i]['content'],json[i]['time']));
   loadHiglight();
  };

 });
}

function loadHiglight() {//为了ajax后重载特效
 $user = $("div .user");
 $text = $("div .text");

 $("div .content").each(function(index) {
  $(this).mousemove(function() {

   $user.eq(index).css("color", "#0A8CD2");

   // $user.eq(index).css("background","#FFE6AD");
   // $text.eq(index).css("background","#FFFDF6");

  }).mouseout(function() {

   $user.eq(index).css("color", "#000");

   // $user.eq(index).css("background","#E6F0F9");
   // $text.eq(index).css("background","#F8FBFD");
  });
 });
}
function createTag(usetName, content, time) {
 var strTag = '

' + usetName + '
' + content + '
' + getLocalTime(time) + '
';
return strTag;
}
function getLocalTime(nS) {
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:d{1,2}$/, ' ');
}The request method is


[php] function data()
{
//Introducing paging class
Include "page.class.php";
//Get the number of data in the data table
$rows = $this->db->count('select * from data');
//Create paging object
$page = new Page($rows, 5, "");
$list=$this->db
->order('id DESC')
//->table('data')
->limit($page->getLimit())
->select();
/*
echo "

";<br>
var_dump($list);<br>
echo "
";
*/
echo json_encode($list);
exit();
}

function data()
{
//Introduce paging class
Include "page.class.php";
//Get the number of data in the data table
$rows = $this->db->count('select * from data');
//Create paging object
$page = new Page($rows, 5, "");
$list=$this->db
->order('id DESC')
//->table('data')
->limit($page->getLimit())
->select();
/*
echo "

";<br>
var_dump($list);<br>
echo "
";
*/
echo json_encode($list);
exit();
}
In this way, the waterfall flow effect is achieved. The disadvantage is that if it is loaded to the end, there is no prompt, hahahaha,

[php] function add(){
//After adding, return the number of affected items. If it is greater than 0, it means the addition is successful
               $json['state']='no';
If (empty($_POST['userName'])) {
                    $json['error']='No username entered';

              }elseif(empty($_POST['content'])){
                   $json['error']='No message content entered';

               }elseif(empty($_POST['email'])){
                  $json['error']='No email entered';

              }else{
isset($_POST['content'])?$_POST['content']=nl2br($_POST['content']):"";
                    $_POST['time']=time();
If($this->db->data($_POST)->add()>0){
                       /*
echo "Added successfully";
                                          // echo "<script>location.reload()</script>";//Prevent repeated submission of the refreshed form
Header("HTTP/1.1 303 See Other");
                     Header("Location: "); //Redirect to the root directory
exit;
                                                                                            $json['state']='ok';
                       $json['data']=$this
->db
->table('data')
->where('id='.$this->db->last_insert_id())
->select();
                                                                                                                                                                                       $json['error']=$this->db->error();
//die($this->db->error());//Add failure output error message
                                                                                                                                                                                                                                 echo json_encode($json);
                    //var_dump($_POST); 
         } 

function add(){

//After adding, return the number of affected items. If it is greater than 0, it means the addition is successful

$json['state']='no';
If (empty($_POST['userName'])) {
$json['error']='No username entered';

}elseif(empty($_POST['content'])){

$json['error']='No message content entered';


}elseif(empty($_POST['email'])){

$json['error']='No email entered';


}else{

isset($_POST['content'])?$_POST['content']=nl2br($_POST['content']):"";

$_POST['time']=time();
If($this->db->data($_POST)->add()>0){
/*
echo "Added successfully";
//echo "<script>location.reload()</script>";//Prevent repeated submission of the refreshed form
Header("HTTP/1.1 303 See Other");
Header("Location: "); //Redirect to the root directory
exit;
*/
$json['state']='ok';
$json['data']=$this
->db
->table('data')
->where('id='.$this->db->last_insert_id())
->select();
}else {
       
$json['error']=$this->db->error();
//die($this->db->error());//Add failure output error message
}  
}
echo json_encode($json);
//var_dump($_POST);
}This is the code for the message part, haha, so that you can see the effect directly on the page after leaving a message without refreshing the browser. The effect is much more beautiful. jquery+ajax is awesome. Haha

2. PHP functions learned today

[php]  json_encode();

说明

string json_encode ( mixed $value [, int $options = 0 ] )

Returnvalue JSON form of value< ;/P>

empty() If the value is empty, return True, returns false if there is a value,

time() Get timestamp

mysql_insert_id() returns the last operation increment Field id

json_encode(); Description string json_encode ( mixed $value [, int $options = 0 ] ) returns the JSON form of value empty() If the value is empty, it returns true, if there is a value, it returns false,
time() gets timestamp
mysql_insert_id() returns the id of the incremented field in the last operation

3. The javascript function we learned today, this function is used to convert timestamps.

[javascript] function getLocalTime(nS) {
Return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:d{1,2}$/, ' ');
}
jquery's append() is used to load the last HTML
in the tag
prependTo() loads HTML code to the front of the tag

function getLocalTime(nS) {
return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:d{1,2}$/, ' ');
}
jquery's append() is used to load the last HTML

within the tag

prependTo() loads HTML code to the front of the tag


4. The experience gained today is that after ajax loads a web page tag, the jquery special effects will disappear. Therefore, after ajax loads a web page tag, jquery events and functions must be re-bound. Otherwise, the special effects will be lost.

[javascript]

<PRE class=javascript name="code">

 
 

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477418.htmlTechArticleOkay, let’s take a look at the picture above. This is an ajax message board. It has a waterfall flow effect, ha 1 .Today I learned jquery’s ajax and went directly to the code [php] / JavaScript Document $(document).ready(function(e...
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