web服务器与网页表单通信,前端与后端通信的几种方式

只有知道了历史,才能更好的把握现在和未来。

在项目中,通常前端开发主要完成两件事情,一是界面搭建,一是数据交互。

下面是我总结前端与后端交互的几种方式,本文只作简单介绍,不做深入了解。

一、AJAX

简述

AJAX(Asynchronous Javascript And XML),是一种使用 XMLHttpRequest 技术构建更复杂,动态的网页的编程实践。

XMLHttpRequest(XHR)对象由微软引入,首次在 IE5 上实现,是一种支持异步请求的技术,用于与服务器交互。XMLHttpRequest 可以在不刷新页面的情况下请求 URL 获取服务器数据,然后使用 JavaScript 操作 DOM 更新页面数据,是 AJAX 编程技术的核心。 这样网页在不影响用户操作的情况下,就可以更新页面的局部内容,用户体验由此得到了很大的提升。在此之前,要实现这种 AJAX 式的通信则要采用内嵌框架或隐藏框架等 hack 手段才能实现。

除了原生 JS 外,jQuery、Axios、vue-resource 都可以实现 Ajax 编程。

原生JS

var url = 'https://api.github.com/users/chriscoyier/repos'

var xhr = new XMLHttpRequest()

xhr.open('GET', url, false)

xhr.onreadystatechange = function(){

if(xhr.readyState === 4) {

if(xhr.status === 200 || xhr.status === 304) {

console.log('response:', xhr.response)

}

}

}

xhr.send()

复制代码

封装起来

var Ajax = {

get: function(url, callback){

var xhr = new XMLHttpRequest()

xhr.open('GET', url, false)

xhr.onreadystatechange = function(){

if(xhr.readyState === 4) {

if(xhr.status === 200 || xhr.status === 304) {

console.log(xhr.response)

callback(xhr.response)

}

}

}

xhr.send()

},

post: function(url, data, callback){

var xhr = new XMLHttpRequest()

xhr.open('POST', url, false)

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

xhr.onreadystatechange = function(){

if (xhr.readyState === 4) {

if (xhr.status === 200 || xhr.status === 304) {

console.log(xhr.response)

callback(xhr.response)

}

}

}

xhr.send(data)

}

}

复制代码

jQuery

jQuery 下实现 Ajax 非常简单

$(function(){

const list = {}

const url = ''

$.ajax({

type: "POST",

contentType: "application/json;charset=UTF-8",

url: url,

data: JSON.stringify(list),

success: res => console.log('res', res),

error: err => console.log('err', err)

})

})

复制代码

vue-resource

vue-resource 是 vuejs 的一个插件,在 vue1.x 的时候被广泛使用,可以通过 XMLHttpRequest 或 JSONP 发送请求和处理响应数据。

vue-resource 可以通过 JSONP 发送请求获取数据意味着其支持跨域

通过 npm 或者 yarn 安装

$yarn add vue-resource

$npm install vue-resource

复制代码

通过 CDN 引入

复制代码

使用

this.$http.get('https://api.github.com/users/chriscoyier/repos')

.then(res => console.log('res:', res.body),err => console.log('err:', err))

复制代码

Axios

Axios 可以用在浏览器和 node.js 中,是一个基于 promise 的 HTTP 库,是 vuejs 官网推荐使用的一种方式。

使用 npm

$npm install axios

复制代码

使用 bower

$bower install axios

复制代码

使用 cdn

// 同步最新版本,但不建议使用,会出现访问不了的问题

// 建议使用指定版本的方式

复制代码

完成请求

axios.get('https://api.github.com/users/chriscoyier/repos')

.then(res => console.log('res:', res.data),err => console.log('err:', err))

复制代码

Promise

使用 ES6 的 Promise 完成 Get 请求

const url = 'https://api.github.com/users/chriscoyier/repos'

const getData = function(url){

const promise = new Promise(function(resolve, reject){

const handler = function(){

if (this.readyState !== 4) {

return

}

if (this.status === 200) {

resolve(this.response)

} else {

reject(new Error(this.statusText))

}

}

const xhr = new XMLHttpRequest()

xhr.open("GET", url)

xhr.onreadystatechange = handler

xhr.responseType = "json"

xhr.setRequestHeader("Accept", "application/json")

xhr.send()

})

return promise

}

getData(url)

.then(res => console.log('data: ', res), err => console.log('err: ', err))

复制代码

二、Fetch

简介

Fetch 基于 Promise,提供了一个获取资源的接口(包括跨域请求)。其全局方法 fetch() 方法要求必须接收一个资源路径,无论请求成功与否,它都返回一个 Promise 对象,resolve 对应请求的 Response。相较于 XMLHttpRequest,它更高效和具有扩展性。

Fetch 的核心在于对 HTTP 接口的抽象,包括 Request,Response,Headers,Body,以及用于初始化异步请求的 global fetch。

使用 Fetch

fetch('https://api.github.com/users/chriscoyier/repos')

.then(res => res.json())

.then(res => {

console.log('res', res[0].blobs_url)

})

复制代码

三、WebSocket

简介

WebSocket 是 HTML5 提供的一种在单个 TCP 连接上进行全双向通讯的网络协议,于 2008 年发布,到 2011 年所有浏览器就都支持了。它的出现弥补了 HTTP 协议只能由客户端向服务器发起请求的缺陷。在此之前,要实现服务器向客户端推送数据只能采取Ajax轮询的方式,即每隔一段时间,就发出一个请求询问服务器有没有新的消息,这种方式导致 HTTP 一直处于打开状态,效率非常低下,因此工程师们发明了 WebSocket。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

下面就是一个 WebSocket 协议,ws 表示协议符,与 https 对应的,wss 表示 ws 的加密形式。端口上与 http 保持了很好的兼容性,也是 80/443,但没有 http 的同源限制,可以任意与服务器通信。

ws://example.com:80/some/path

复制代码

客户端实现

一个网页脚本的例子

// 执行下面语句之后,客户端就会与服务器进行连接。

var ws = new WebSocket("wss://echo.websocket.org");

ws.onopen = function(evt){

console.log("Connection open ...");

ws.send("Hello WebSockets!");

};

ws.onmessage = function(evt){

console.log( "Received Message: " + evt.data);

ws.close();

};

ws.onclose = function(evt){

console.log("Connection closed.");

};

复制代码

四、Form 表单

Form 是 HTML 中的一个元素,表示文档中的某一个区域,通常会有很多子元素,这些子元素提供了交互的作用,用于向 web 服务器提供数据。

Enter your name:

Enter your email:

复制代码

action 表示处理表单提交的 URL。这个值可被 、 或 元素上的 formaction 属性覆盖。

参考文档

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值