Home  >  Article  >  Backend Development  >  php+js+ajax implements simple reply function

php+js+ajax implements simple reply function

藏色散人
藏色散人forward
2019-12-13 17:55:414105browse

php js ajax implements simple reply function (suitable for novices)

Rendering

php+js+ajax implements simple reply function

html code

The layout is not the focus, the writing is very simple

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

css code

<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 code

I use native ones, jquery will be faster, it depends on personal preference

<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 code

But I don’t want to explain too much. Nothing

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

For more PHP related knowledge, please visit PHP Tutorial!

The above is the detailed content of php+js+ajax implements simple reply function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete