Detailed explanation of the use of ajax and cgi communication
这次给大家带来ajax与cgi通信的使用详解,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函数。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of the use of ajax and cgi communication. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
