请使用jq通过get和post调用接口http://index.com数据并接收,get和post传id=99
// $.get("http://http://index.com",{id=99},function(data,status){
// console.log(data);
// });
$.post("http://index.com",{
"id":99
},function(data,status){
console.log(data);
});
js中 ajax调取接口数据 异步
一、 http与https区别
1、https协议需要到ca申请证书,一般免费证书较少,因而需要一定费用。
2、http是超文本传输协议,信息是明文传输,https则是具有安全性的ssl加密传输协议。
3、http和https使用的是完全不同的连接方式,用的端口也不一样,前者是80,后者是443。
4、http的连接很简单,是无状态的;HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议,比http协议安全。
1.创建XMLHttpRequest()对象
let http = new XMLHttpRequest();
2.请求 创建的对象.open("请求方式","url")
get方式 | 偏向获取数据 |
post方式 | 偏向向后端提交数据 |
put方式 | 偏向更新(全部更新) |
delete方式 | 偏向删除信息 |
- get方式
http.open("get","http://jsonplaceholder.typicode.com/posts?id=10");
http.send();
- post方式
http.open("post","http://jsonplaceholder.typicode.com/posts");
// 传值:
// 1)表单格式
http.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
http.send(JSON.stringify(`userId=10&title=hello&body=你好`));
// 2)JSON格式
http.setRequestHeader("Content-Type","application/json")
http.send(JSON.stringify({
"userId":10,
"title":"hello",
"body":"你好"
}))
3.响应(获取接口返回值)http.responseText()获得字符串形式的响应数据。
4.onreadystatechange 监听事件
0: 请求未初始化 |
1: 服务器连接已建立 |
2: 请求已接收 |
3: 请求处理中 |
4: 请求已完成,且响应已就绪 |
监听事件
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==201){
console.log(JSON.parse(http.responseText));
}
}
console.log(http);
jq
$.ajax()默认行为是get
var base = "http://jsonplaceholder.typicode.com";
$.ajax({
url: base+"/posts",//base是"//http.127.0.0.1"
data: {
id:20
},
success: function(user){
console.log(user);
},
})