http概念
客户端与服务器超本文无状态传输协议
http默认端口80
https 默认端口 443
http请求方法
方法 | 描述 |
---|---|
options | 测试有哪些方法可以用 |
get | 获取服务信息 |
post | 修改与更新,新增服务器信息 |
put | 新增 |
delete | 删除 |
head | 只返回头信息 |
trace | 回显头信息 |
connect | 管道形式连接 |
http请求过程
建立tcp连接 客户端发送请求头+请求体 服务器响应请求头+请求体 ,关闭tcp连接 客户端渲染内容
1.客户端发起 http请求 建立tcp连接
2. 客服端(浏览器)发送请求信息(状态行 请求头 空行 请求体)
3. 服务的响应请求信息(状态行 响应头 空行 响应体)
4. 客服关闭tcp网络连接
5. 客户端(浏览器)渲染内容
ajax(异步的javascript and xml)
ajax原理
1.通过 XMLHttpRequest 与服务器交换数据
2.服务数据通过json 或者 xml格式返回
3.浏览器端通过js+ccs渲染展示数据
ajax的GET请求方法
- 创建xhr
- open打开连接
- 监听readystate readyState 4准备状态完毕 status 状态码200 响应成功
- send 发送
<button type="button" id="btn">发送</button>
<p id="content"></p>
<script>
btn.onclick = function(){
var xhr = new XMLHttpRequest();
xhr.open("GET","./be.txt",false);
xhr.onreadystatechange = function(){
if(xhr.status == 200&&xhr.readyState==4){
content.innerHTML = xhr.responseText;
}
}
xhr.send();
}
</script>
点击按钮时,be.txt中的内容显示在p标签内
ajax的POST请求方法
- 新建ajax对象 var xhr = new XMLHttpRequst()==
- 打开连接==xhr.open(“POST”,url,fasle)
- 设置头信息(get省略) xhr.setRequestHeader(‘Content-Type’,‘application/x-www-form-urlencoded’);
- 监听事件。 xhr.onreadystatechange = function(){
if(xhr.readyState == 4&&xhr.status == 200){content.innerHTML = xhr.responseText;}} - 发送 xhr.send(“name=mumu&age=18”)
<input type="text" id="name" value="" />
<input type="text" id="age" value="" />
<button type="button" id="btn">发送</button>
<p id="content"></p>
<script>
btn.onclick = function(){
var xhr = new XMLHttpRequest();
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
xhr.open("POST","https://www.520mg.com/ajax/echo.php",false);
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
content.innerHTML = xhr.responseText;
}
}
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(`name=${name} & age=${age}`);
}
</script>
jquery中的ajax
- 第一层:$.ajax()
- 第二层:$.get 与 $.post(url,data,function(data,status,xhr))
- 第三层:(1)$.getJSON() (2) $.getScript() (3) load()
** 其中$.post又分为三种:**
- 回调函数 $.get(url,function(data,status,xhr){})
- .done() .fail() .always()
- .then() .catch()
url组成
https:www.520mg.com:443/ajax/echo.phpname=mumu&age=18#cate为例:
https 协议
www子域名
520mg.com 域名
:443 端口号
/ajax/echo.php 路径
?name=mumu&age=18 查询条件
#cate 哈希值
浏览器同源策略
当浏览器去访问服务器资源(ajax) 要求服务器的地址与浏览器同源
协议,域名,子域名,端口号要一致
跨域
绕过浏览器的同源策略,请求到数据
跨域方式
- 服务器响应头信息跨域 Access-Control-Allow-Origin: *
- jsonp跨域
- 服务器代理(开发)
异步,同步
同步胡阻塞代码执行