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!

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.


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

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!
