PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php+js+ajax实现简单的回帖功能

藏色散人
藏色散人 转载
2019-12-13 17:55:41 3996浏览

php+js+ajax实现简单的回帖功能(适合新手)

效果图

d28d00e442c416a6c837f7fdcf3b46f.png

html代码

布局不是重点,写的很简单

<div>
            <ul>
                <l1>张三:"今天天气很不错"  <button>回复</button></l1>
            </ul>
        </div>

css代码

<style>
            div{width:600px;margin:auto;border:1px solid #ccc;}
            ul{list-style: none;}
            ul li{line-height: 50px;}
            input{margin-right:10px;}
    </style>

js代码

我用的都是原生,jquery会快一些,看个人喜好吧

<script>
  var btn=  document.querySelector(&#39;button&#39;);//获取“回复”按钮
  var ul=  document.querySelector(&#39;ul&#39;);//获取ul
  //document.querySelector这种选择元素的方式与jquery基本一致,推荐使用(尽管部分低版本浏览器有兼容问题)
  
 //为回复按钮注册点击事件
  btn.onclick=function(){
    var li=document.createElement(&#39;li&#39;);//动态创建li标签,用来盛放接下来的输入框和确认按钮
    var input1=document.createElement(&#39;input&#39;);//动态创建input标签
    input1.type="text";//设置类型为文本框,如果回复内容多,文本域好一些
    var input2=document.createElement(&#39;input&#39;);//动态创建input标签
    input2.type="button";//设置类型为按钮
    input2.value="确认";
    li.appendChild(input1);//将设置好的输入框和按钮放进li容器
    li.appendChild(input2);
    ul.appendChild(li);//将设置好的盛有输入框和按钮的li放进ul容器
    
//推荐动态元素绑定事件用事件委托,这里简写了
//为确认按钮绑定事件
    input2.onclick=function(){
    var info=input1.value;//获取文本框的值
    var xhr=new XMLHttpRequest();//创建ajax对象
    xhr.open("get","do.php?info="+info);//这里采用get方式发送,参数的问题后边会提到
    
    //xhr.onload有兼容问题,但是简单,也可以监听状态,因人而异
    xhr.onload=function(){
       
            if(xhr.responseText=="ok"){
            //移除之前创建的文本框和确认按钮,将回复内容写入li容器
                li.removeChild(input1);
                li.removeChild(input2);
                li.innerHTML="<?php echo "李四:";?>"+info;//人名实际开发用session,PHP中$_SESSION["name"]
                
            }
    }
     xhr.send(null);
    }
  }
   
    </script>

php代码

不过多解释了,没啥东西

<?php  
if(isset($_GET[&#39;info&#39;])){//关于之前ajax传递的参数,判断是否存在
    echo "ok";
}
?>

更多PHP相关知识,请访问PHP教程

声明:本文转载于:csdn,如有侵犯,请联系admin@php.cn删除