整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

前后端数据交互(二)-原生 ajax 请求详解

、ajax介绍

ajax 是前后端交互的重要手段或桥梁。它不是一个技术,是一组技术的组合。

ajax :a:异步;j:js;a:和;x:服务端的数据。

ajax的组成:

  • 异步的 js 事件
  • 其他 js (处理解析数据)
  • XMLHttpRequest 对象
  • 数据(txt、json、xml、html)

通过后台与服务器进行少量数据交换,ajax可以使网页实现异步更新。也就是在不需要重新加载整个网页的情况下,能够更新部分网页的技术。传统的网页不使用ajax,如果需要更新内容,必须重新加载整个页面。

ajax请求原理:创建一个网络请求对象 -> 发送连接请求 -> 发送请求数据 -> 检查网络请求对象的状态 -> 如果响应成功了 -> 浏览器接收返回数据并更新网页。接下来详细介绍对象的创建以及它的方法。

二、创建 XMLHttpRequest 对象

XMLHttpRequest 对象,用于后台与服务器之间的数据交换,意味着可以在不加载整个网页的情况下,更新部分内容或数据。现代浏览器基本都支持,但是低版本的IE不支持,如果我们考虑IE兼容问题创建对象的时候需要兼容创建。

考虑兼容时创建的对象:

var xhr ;
if( window.XMLHttpRequest ){ //检查浏览器是否支持XMLHttpRequest
 xhr = new XMLHttpRequest()
}else{
 xhr = new ActiveXObject("Microsoft.XMLHTTP") //兼容IE6  IE5
}

三、XMLHttpRequest的方法

3.1、open( )

设置请求的类型、请求接口、是否异步处理。

使用语法:open( method , url , async )

  • method:设置网络请求的类型,常用的 get 和 post
  • url:设置请求的接口也就是服务器的地址
  • async:true时表示异步,false表示同步

3.2、send( )

将请求发送到服务器。

使用语法:send( string )

  • string,只用在请求方式是post时,发送给服务器的数据。数据是键值对格式的,如:"name=jack&pwd=1234"

使用发送方式不同的时候,传输数据添加方式也不同,所以我们介绍下分别为post和get时,数据是如何发送的?

3.3、提交方式

  • 使用 get 方式提交

get发送请求时,需要传给后台的数据通过url来传递,多个参数之间使用 & 符号连接,使用时如下:

xhr.opn( "GET" , "1.php?name=hello&age=world" , true )
xhr.send()
  • 使用 post 方式提交

使用 post 方式发送请求时,使用send来发送数据,有时需要设置数据格式,类似表单那样,此时可通过 setRequestHeader 设置发送的数据格式

xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded")

Content-type常见类型:

  • text/plain 纯文本,基本不怎么用
  • application/x-www-form-urlcoded 键值对格式传值,多个参数使用&连接
  • multipart/form-data 定界符,分隔各个数据,经常用于上传文件

四、readyState 属性

readyState 存有 XMLHttpRequest 的状态,它的值从 0-4 发生变化,分别代表的意义:

  • 0:请求初始化,对象刚刚创建
  • 1:服务器已连接
  • 2:已发送,send发放已调用
  • 3:已接收,此时只接收了响应(response)头部分
  • 4:已接收,此时接收响应(response)体信息

每当 readyState 状态值发生改变时会,就会触发 onreadystatechange 事件,对应着每个状态值就会被触发五次。当状态值为 4 时表示网络请求响应完毕,就可以获取返回的值。

xhr.onreadystateChange = function(){
 if( xhr.readyState==4 ){
  if( xhr.status>=200 && xhr.status<300 || xhr.status==304 ){
   console.log("请求成功",xhr.responseXML)
  }else{
   console.log("请求失败")
  }
 }
}

五、响应信息

通常我们需要获取服务器返回的信息,然后对我们的网页做相对应的结果展示,通常使用 XMLHttpRequest 的 responseText 或 responseXML 属性。

responseText ---> 获取到的是字符串形式。接收到可直接使用,无需转换。

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

responseXML ---> 获取到 XML 形式的数据。使用时需要解析,如:

<person>
 <name>小米粒</name>
 <age>18</age> 
</person> 
解析时:
document.getElementsByTagName("name")[0]

responseXML 目前已被 json 取代,所以作为了解就好。

六、ajax实例

var xhr ;
if( window.XMLHttpRequest ){
 xhr = new XMLHttpRequest()
}else{
 xhr = new ActiveXObject("Microsoft.XMLHTTP") //兼容IE6  IE5
}
xhr.open('GET','1.txt',true)
xhr.send()
xhr.onreadystatechange = function(){
 if(xhr.readyState==4){
  if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
   console.log("请求成功",xhr.response) // 请求成功 abc
  }else{
   console.log("请求失败")
  }
 }
}

1.txt 文档内容为 abc。所以返回的结果也是abc

hinkPHP6获取参数的方法有多种,初学者可能知道其中的一种,然后在看到其他人代码的时候又换了个写法,可能会一脸懵逼,下面就给大家总结一下ThinkPHP6中获取参数的方法。

假设我们有以下4种请求URL:

① http://localhost/index/index/user/id/1.html

② http://localhost/index/index/user?id=1

③ http://localhost/index/index/user?name=admin

④ http://localhost/index/index/user?name=111admin222

一、使用助手函数,这是最简单直接的:

var_dump(input('id')); // ①、②链接都是1,③、④都是NULL

二、使用依赖注入

$this->request->param(); // 该方法返回所有的参数,返回值是一个数组
$this->request->param('id'); // 获取指定参数的值
$this->request->get('id'); // 只对②链接生效,获取id的值
$this->request->param('id', 1, 'intval'); // 接收参数id的值并转成整型,结果为1

三、使用门面模式的静态方法获取

注意:使用该方法之前需要先引入:use think\facade\Request;

Request::param(); // 获取当前请求的所有变量
Request::param('name'); // 获取请求的name值,返回字符串,如果没有传值,则返回null
Request::param(['name', 'email']); // 获取多个参数值

其中,还有has方法可以检测变量是否已经设置,如:

Request::has('id', 'get');
Request::has('name', 'post'); // 检测是否有POST方法传递的name值,有的话返回true,反之为false。

变量检测可以支持所有支持的系统变量,包括get/post/put/request/cookie/server/session/env/file

以上三种方法是TP6获取参数的归纳总结,在很多情况下,我们需要判断当前操作的请求类型是哪一种,如:GET、POST、PUT、DELETE或者是HEAD等等,同时不仅需要针对不同的请求类型做出相应的逻辑处理,更要兼顾安全性的验证,过滤非法请求,TP6框架提供了请求对象Request类的多种方法来获取、判断当前请求类型,例如,判断一个请求是否为POST请求,我们可以这样做:

if($request->isPost()) {
  // TODO
}

类似的情形还有$request->isGet()、$request->isPut()、$request->isAjax()等等,具体的方法如下图:

请求对象Request类提供的方法

注意:method方法返回的请求类型始终是大写的,并且这些方法都不需要传入任何参数。

以上就是ThinkPHP6中获取参数的三种方式,以及一些相关的请求类型,可能还不是很全,但是掌握这些基本能满足大部分情形下的参数获取,如果想了解更多相关内容,请移步ThinkPHP官网查看相关文档。

文分享自华为云社区《浅谈Tomcat之Servlet-request获取请求参数及常用方法-云社区-华为云》,作者:QGS。

//获取Map集合中所有的key
Enumeration<String>   getParameterNames();
//获取Map
Map<String, String[]>   getParameterMap(); 
//根据key获取Map集合中的vale  (常用**)
String[]   getParameterValues(String s);
//获取value一维数组的第一个元素   (常用**)
String    getParameter(String name); 
浏览器向服务器提交的是String类型


//getParameterNames()获取所有key值
Enumeration<String> keys = request.getParameterNames();
while (keys.hasMoreElements()){
    String key = keys.nextElement();
    System.out.print("key: "+key +" ");
    //getParameterValues(key) 、据key获取Map集合中的vale
    String[] Values = request.getParameterValues(key);
    if (Values.length>1){
        for (String value : Values) {
            System.out.print("value:"+value+" ");
        }
    }else {
        System.out.print(Values[0]);
    }
    System.out.println();
}

通过标签中的name获取value一维数组

getParameterNames()获取所有key值

如果html页面的数据有更改,浏览器清除过缓存在执行。

//通过标签中的name获取value一维数组
String[] usernames = request.getParameterValues("username");
String[] pwds = request.getParameterValues("pwd");
String[] hobbies = request.getParameterValues("hobby");
for (String username : usernames) {
    System.out.print(username);
}
System.out.println();
for (String pwd : pwds) {
    System.out.print(pwd);
}
System.out.println();
for (String hobby : hobbies) {
    if (hobby.isEmpty()){
        System.out.println("null");
    }
    System.out.print(hobby);
}
System.out.println();

//获取数组的第一个参数
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
String hobby = request.getParameter("hobby");

System.out.println("getParameter :"+username+" "+pwd+" "+hobby);

getParameter获取数组的第一个参数

//获取数组的第一个参数
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
String hobby = request.getParameter("hobby");

请求域对象

Request又称“请求域”
应用域对象ServletContext(Servlet上下文对象)、
当用户的共享数据很少修改操作并且数据量少的时候,使用ServletContext能够提升程序的执行效率(应用域绑定数据,看作将数据放到Cache当中,用户访问时直接从Cache中提取,减少IO等操作)。
应用域对象ServletContext的操作方法(类似Map集合的操作)
//向域绑定数据
setAttribute(String name , Object obj)
//从域获取数据,根据name(key)获取数据
Object getAttribute(String name)
//移除数据,根据name(key)
removeAttribute(String name)
请求域对象
请求域比应用域的范围小, 占用资源小,生命周期短,请求域对象只在一次请求内有效。
请求域对象ServletContext的操作方法(类似Map集合的操作)
//向域绑定数据
setAttribute(String name , Object obj)
//从域获取数据,根据name(key)获取数据
Object getAttribute(String name)
//移除数据,根据name(key)
removeAttribute(String name)

案例

//获取系统当前时间

Date nowTime =new Date();

//向request域 中绑定数据

request.setAttribute("NowTime",nowTime);

//从request域 获取数据

Object obj = request.getAttribute("NowTime");

response.setContentType("text/html;charset=utf-8");

response.setCharacterEncoding("utf-8");

PrintWriter out = response.getWriter();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");

String timeStr = sdf.format((Date)obj);

out.print("当前时间: "+ timeStr);

Servlet转发机制

转发servlet类

public class ServletA extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用Servlet转发机制。执行ServletA后,跳转至ServletB,调用请求转发器,将request,response参数传递给另一个HttpServlet子类
        request.getRequestDispatcher("/servletB").forward(request,response);
    }
}
public class ServletB extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取系统当前时间
        Date nowTime =new Date();
        //向request域 中绑定数据
        request.setAttribute("NowTime",nowTime);
        //从request域 获取数据
        Object obj = request.getAttribute("NowTime");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        String timeStr = sdf.format((Date)obj);
        out.print("当前时间: "+ timeStr);
    }
}

转发html页面

//既可以转发Servlet类也可以转发html(属于Web容器当中合法的资源都可以转发)
request.getRequestDispatcher("/share.html").forward(request,response);

常用方法

//获取客户端的IP地址
String remoteAddr = request.getRemoteAddr();
//获取远程的用户
String remoteUser = request.getRemoteUser();
//获取远程的主机IP
String remoteHost = request.getRemoteHost();
//获取远程的的端口
int remotePort = request.getRemotePort();
//获取主机服务名
String serverName = request.getServerName();
//获取服务路径(项目名称)
String servletPath = request.getServletPath();
//获取服务端口
int serverPort = request.getServerPort();
//获取Servlet上下文  或者this.getServletContext();
ServletContext servletContext = request.getServletContext();
//指定字符集(解决不同字符集乱码问题)
response.setCharacterEncoding("utf-8");

点击下方,第一时间了解华为云新鲜技术~

华为云博客_大数据博客_AI博客_云计算博客_开发者中心-华为云

#华为云开发者联盟#