目录
一、AJAX异步请求
1、基本概念
- AJAX(Asynchronous JavaScript and XML)是一种用于在网页中创建异步通信的技术。它允许网页在不重新加载整个页面的情况下,与服务器进行数据交换。这使得网页可以动态地更新部分内容,提供更流畅的用户体验。例如,在一个社交网站上,用户可以在不刷新整个页面的情况下,通过 AJAX 发送新的消息或者获取最新的动态。
异步请求一般的方法是GET、POST、PUT、Delete等。
ES6(ECMAScript核心语法)提供一个fetch函数,基于promise方式。
2、使用方法
fetch函数的使用方发:
GET和DELETE
fetch(url)
.then(response->response.json())
.then(data=>{})
.catch(error=>{})
POST和PUT
fetch(url,{method: "POST|PUT", body:"", headers:{} })
.then()...
其中method:请求方法
body:请求体的数据
headers:请求头
请求头的属性
补充Basic 认证原理:
- Basic 认证是一种简单的 HTTP 认证方式。当客户端(如浏览器)向服务器请求一个受保护的资源时,服务器会返回一个
401 Unauthorized
状态码,并在WWW - Authenticate
响应头中指定Basic
认证方式。
content-type:请求体数据类型,一般设置为 application/xx-www-form-urlencoded(form表单数据,数据格式,字段名=值&字段名=值....)
也可以设置为 applicatio/json json的数据格式
将js数组转换为数组的字符串对象: JSON.stringify( [ ] )
将json格式的字符串转换为js对象: JSON.parse( )
content-length:数据长度
cookis:浏览器存储的cookie信息,是由服务器发送给浏览器的
authentication:请求身份信息,一般是
Basic认证 base64(username,password)
Token 32位长度的令牌(与传统的认证方式不同,token是由服务器进行有效期限的加密)
补充
HTTP请求报文头第一行
请求方法 请求资源路径 协议类型/版本号
请求方法 :GET POST PUT DELETE HEAD OPTIONS
请求资源路径:路径 /$rdgate
路径参数:ID=1234....324,如果有多个参数以&分割,如a=1&b=2
路径和参数的分割符是?
协议类型/版本号:HTTP HTTPS 1.0 1.1 2.0 通常使用1.1
例如
POST /$rdgate?ID=974C4D33DEEB425A HTTP/1.1\r\n
HTTP响应报文头第一行
协议类型/版本号 状态码 状态码说明
常见状态码在我另外一篇,去我主页搜索常见状态码
例如
HTTP/1.1 200 OK\r\n
示例1:fetch发起get请求
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="Era">
<meta name="keywords" content="AJAX的GET请求">
<title>AJAX的异步请求</title>
</head>
<body>
<div id="ret"></div>
<script>
window.onload = function () {
// 当面页加载完成后,则执行的程序
// 发起异步请求(HTTP):
// 1)请求方法 fetch()
// 2) 请求头和请求体的数据怎么放
// 3)响应的数据怎么接
let url = "/cgi-bin/data1.cgi";
// 发起get请求, 为了查询数据(从后端获取数据)
fetch(url).then(resp => resp.json()).then(data => {
console.log(data);
ret.innerText = "id=" + data.id + ",name=" + data.name;
})
}
</script>
</body>
</html>
示例1:fetch发起post请求
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="Era">
<title>登录页面</title>
</head>
<body>
<form onsubmit="return login(this);">
<div>
<label>用户名</label>
<input name="name">
</div>
<div>
<label>口 令</label>
<input name="pwd" type="password">
</div>
<div>
<button>登录</button>
</div>
</form>
<script>
function login(form) {
// 创建了js对象 ,只包含属性的对象即为json对象
let login_data = {
name: form.name.value.trim(),
pwd: form.pwd.value.trim()
};
// JSON.stringify(login_data) 将login_data对象转化json格式的字符串
fetch("/cgi-bin/login.cgi", {
method: "POST",
body: JSON.stringify(login_data),
headers: {
"Content-Type": "applicaiton/json;charset=utf-8"
}
}).then(resp => resp.json()).then(data => {
console.log(data);
// 判断是否登录成功,成功时打开css3.html页面
if (data.code == 0) {
open("/css3.html", "_self");
} else {
// 如果失败,则弹出对话框,显示登录失败的消息
alert(data.msg);
}
})
return false;
}
</script>
</body>
</html>
二、CGI开发
1、基本概念
CGI(Common Gateway Interface)通用网关接口,是HTTP与其他程序“交谈”的工具,通过CGI接口就可以实现在服务器上运行其他程序。
CGI可以是任意一种编程语言,只要这个语言具有标准输入输出和获取环境变量
2、CGI的处理步骤
1、通过浏览器将用户请求发送到服务器
2、服务器接受到用户请求并交给CGI程序处理
3、CGI程序把处理好的结果传回服务器
4、服务器把结果送回浏览器
CGI 环境变量名称 | 说明 |
REQUEST_METHOD | 请求类型,如“GET”或“POST23 |
CONTENT_TYPE | 被发送数据的类型 |
CONTENT_LENGTH | 客户端向标准输入设备发送的数据长度,单位为字节 |
QUERY_STRING | 查询参数,如“id=10010&name=Era" |
SERVER PROTOCOL | 服务器协议,如:HTTP/1.1 |
获取环境变量的方法:getenv("环境变量名")
2、使用方法
示例1:相应json数据
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("content-type: application/json; charset=utf-8\r\n");
printf("\r\n\r\n");
printf("{\"id\": 1, \"name\": \"Era\"}");
return 0;
}
示例2: 解析json的数据-登录用户的json数据
下载cJSON源码:git clone https://gitee.com/du-yueqiang/cJSON.git
进入cJSON目录,执行sudo make和sudo make install即可。安装的位置/usr/local位置上 引入头文件<cjson/cJSON.h>
编译时: 加 -lcjson 第一次编译之后, 需要执行 sudo ldconfig, 将/usr/local/lib路径加入到so库加载的环境中。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <cjson/cJSON.h>
int main(int argc, char const *argv[])
{
// 获取上传的数据
char request_data[128] = "";
fgets(request_data, 128, stdin);
// int fd = open("tmp.txt", O_CREAT | O_WRONLY, 0666);
// write(fd, request_data, strlen(request_data));
// 要求:请求上传的数据类型必须是json格式的字符串
cJSON *p = cJSON_Parse(request_data);
cJSON *name = cJSON_GetObjectItemCaseSensitive(p, "name");
cJSON *pwd = cJSON_GetObjectItemCaseSensitive(p, "pwd");
printf("content-type: application/json;charset=utf-8\r\n");
printf("\r\n");
if (strncmp(name->valuestring, "Era", 5) == 0 &&
strncmp(pwd->valuestring, "123456", 6) == 0)
{
printf("{\"code\": 0, \"data\": {\"user_id\": 111, \"nickName\": \"小怪
\"}}");
}
else
{
printf("{\"code\": 1, \"msg\": \"用户名或口令错误\"}");
}
// write(fd, name->valuestring, strlen(name->valuestring));
// write(fd, pwd->valuestring, strlen(pwd->valuestring));
// close(fd);
return 0;
}
示例3: 生成json数据
#include <stdio.h>
#include <cjson/cJSON.h>
int main(int argc, char const *argv[])
{
cJSON *obj1 = cJSON_CreateObject();
cJSON_AddItemToObject(obj1, "name", cJSON_CreateString("Era"));
cJSON_AddItemToObject(obj1, "id", cJSON_CreateNumber(1001));
char *json_data = cJSON_Print(obj1);
printf("%s", json_data);
return 0;
}