Ajax and cgi communication under Boa server (graphic tutorial)
最近我在研究嵌入式开发的课程设计,接下来通过本篇文章给介绍了Boa服务器下的ajax与cgi通信的相关资料,非常不错,具有参考借鉴价值,感兴趣的朋友一起看下吧
最近在最有做一个嵌入式课程设计,要求是利用基于cortax a8的物联网实验箱做一个简单的嵌入式网页交互系统作为课程设计来验收评分。因为本身自己是学前端的,所以网页部分并不是重点,主要是和boa服务器之间的通信,课程实验给的例子是直接使用printf来打印html标签形成新的页面,有过前端开发经验的人都知道这种做法效率低下而且没有办法实现异步刷新,所以博主采用ajax来进行boa服务器下的异步通信。
主要实现及踩过的坑如下:
1. get 还是 post请求:怎么发请求参见W3School上的ajax教程
推荐一般人没有前端基础的人使用get请求,因为只需要在请求的参数做一个字符串拼接就可以完成基本的ajax请求,具体实现可以参照一下这个网址(http://blog.csdn.net/huguohu2006/article/details/7755107),接下来重点讲一下post请求,优势这里我就不多讲了,前面的教程里面都有,主要讲一下实现方式:
function sender(url, data) { var xhr = createXHR(); if (xhr) { xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); console.log(xhr.responseText.toString()); var returnValue = xhr.responseText.toString(); console.log(returnValue); return returnValue; // firefox下xhr.responseText作为返回值失效的问题 // ie可以利用return来得到值。但firefox则不能,只能在readyState == 4 && status == 200时处理一个函数 // 这个函数应当作为一个参数传递入函数。有个奇怪现象你如果去除红线部分的注释,firefox又可以取到值。 // 估计是firefox使用ajax取值有个延时造成。 //return xhr.responseText.toString(); } }; xhr.open("post", url, true); // send(string) 仅适用于post请求 xhr.send(data); } else { //XMLHttpRequest对象创建失败 alert("浏览器不支持,请更换浏览器!"); } }
利用调用sender函数来实现ajax,函数的两个参数分别是请求的url和要发送的数据,注意post请求只能发送string类型的数据。如果要发送其他类型的数据建议采用jquery封装的ajax方法,这里之所以采用原生的ajax方法来发送数据主要有以下几个原因:
•jquery库的体积比较大,有可能mount进开发箱上的linux系统时出现失败的情况,这种情况可以通过mount u盘的方式解决 mount u盘的命令如下: mount -r /dev/uba4 /web -r为mount进文件的读写权限,具体可执行搜索查询,uba4为U盘在linux系统上显示的名字,web为目标文件夹,使用U盘挂载的缺点在于整个U盘的文件会全部被复制到目标文件夹中,有点缀余
•发送的数据不很多,也没有其他的类型要求,使用string类型完全可以满足开发需求,没必要引入jquery库增加项目空间
•原生的ajax可以更好地解释http请求的原理
下面再介绍一下cgi文件对http请求的处理,示例函如下:
#include <stdlib.h> #include <stdio.h> #include <string.h> char* get_cgi_data(FILE* fp, char* method) { char* input; int len; int size=1024; int i=0; if (strcmp(method, "GET") == 0) /**< GET method */ { input = getenv("QUERY_STRING"); return input; } else if (strcmp(method, "POST") == 0) /**< POST method */ { len = atoi(getenv("CONTENT_LENGTH")); input = (char*)malloc(sizeof(char) * (size+1)); if (len == 0) { input[0] = '\0'; return input; } while (1) { input[i] = (char)fgetc(fp); if (i == size) { input[i+1] = '\0'; return input; } --len; if (feof(fp) || (!(len))) { i++; input[i] = '\0'; return input; } i++; } } return NULL; } int main(void) { char* input; char* method; char name[64]; char passwd[64]; int i=0; int j=0; printf("Content-type:text/html\n\n"); printf("The following is query result:"); method = getenv("REQUEST_METHOD"); input = get_cgi_data(stdin, method); printf("string is: %s", input); return 0; }
上面包含了c语言处理两种请求的方法,get请求比较简单,直接使用getenv("QUERY_STRING")就可以获取到请求发送的数据,post请求的处理则比较负责,先获取请求内容长度,然后根据长度来动态分配一个等长的字符串空间,将发送的数据传给字符串,然后再根据自己项目的需要进行相应的处理即可。
PS:发送http请求时对应的成功程序printf之后就是http请求接受到的相应,也就是对应的xhr的responseText属性值,另外.c文件需要理由arn-linux-gcc -o helloworld.cgi helloworld.c命名交叉编译得到对应的.cgi文件。然后博主用的是在每一次请求成功之后继续发送下一次请求,因为如果直接使用setInterval函数进行循环请求传感器数据的话会产生比较大的延时,基本等同于进程,如果直接通过文件存储传感器数据的方式则可以使用setInterval函数。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of Ajax and cgi communication under Boa server (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software