当前位置: 移动技术网 > IT编程>网页制作>CSS > Ajax请求后台数据

Ajax请求后台数据

2019年01月11日  | 移动技术网IT编程  | 我要评论

一、前期准备

安装好xampp软件,并运行起来。本文代码是基于xampp开发环境,xampp是完全免费且易于安装的apache发行版,其中包含mariadb、php和perl。xampp开放包的设置让安装和使用出奇容易。

二、前后台数据交互

前台部分
其中“process.php?name=herry”,向后台传递name数据

 document.getelementbyid("button").addeventlistener("click",function () {
        var xhr = new xmlhttprequest();
        xhr.open("get","process.php?name=herry",true);
        xhr.onreadystatechange=function () {
            if(xhr.readystate==4&&xhr.status==200) {
                var data = xhr.responsetext;
                console.log(data)
            }
        };
        xhr.send();
    })

后台php部分
后台接收了name数值,并向前台返回了"get: 你的名字是". $_get['name']


于是最后前台console里面得到:get: 你的名字是herry

 

三、正常表单提交到php与ajax方式提交

正常表单get提交数据到php

前台部分


 

后台php部分


表单输入名字bucky,然后点击提交后,将数据打包后,传递给后台,最后后台返回我们想要的数据----get: 你的名字是bucky。整个过程中页面有刷新,数据点击提交后,页面跳转到这个网址https://localhost/ajax/process...

 

ajax请求后台数据get

ajax异步请求数据,无需刷新页面。可以提高用户体验,较少网络数据的传输量。click事件改成submit事件(表单应该用submit事件),然后取消默认事件。

前台部分

//html部分
 
//javascript部分 document.getelementbyid("getform").addeventlistener("submit",function(e){ e.preventdefault();//阻止默认跳转事件 var name=document.getelementbyid("name1").value;//获取输入的值 var xhr = new xmlhttprequest(); xhr.open("get","process.php?name="+name,true); xhr.onreadystatechange=function () { if ( xhr.status == 200&&xhr.readystate == 4) { var data = xhr.responsetext; console.log(data); } } xhr.send(); })

后台php部分


在表单输入bucky,点击提交,最后在console显示:get: 你的名字是bucky。整个过程页面无刷新,有效提高页面性能。

 

正常表单post提交数据到php

与get提交数据差不多
前台部分


 

后台php部分


表单输入名字bucky,然后点击提交后,浏览器将数据打包后,传递给后台,最后后台返回我们想要的数据----post: 你的名字是bucky。整个过程中页面有刷新,数据点击提交后,页面跳转到这个网址https://localhost/ajax/process...。与get方式提交不同的是,post方法数据并没有内嵌在url中,这样安全性比较高。

 

ajax请求后台数据post

post请求与get主要有两点不同:

①post请求一定要设置请求头的格式内容:

xhr.setrequestheader("content-type","application/x-www-form-urlencoded");  

②post请求参数放在send里面,即请求体

xhr.send("name="+name" );  

前台部分

//html部分
 
//javascript部分 document.getelementbyid("postform").addeventlistener("submit", function (e) { e.preventdefault(); var name=document.getelementbyid("name2").value; var params = "name="+name; var xhr = new xmlhttprequest(); xhr.open("post","process.php",true); xhr.setrequestheader("content-type","application/x-www-form-urlencoded"); xhr.onreadystatechange=function () { if(xhr.readystate==4&&xhr.status==200) { var data = xhr.responsetext; console.log(data); } }; xhr.send(params); })

后台php部分


表单输入名字bucky,然后点击提交后,最后在console显示:post: 你的名字是bucky。整个过程页面无刷新。

 

四、总结

1.在不需要重新刷新页面的情况下,ajax 通过异步请求加载后台数据,提高用户体验和页面性能。
2.get参数通过url传递,post放在request body中,后者安全性比较高。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网