In Web programming, CGI is required to respond to the interaction with hardware. Generally, we use Form actions to interact with CGI. However, to use Form to interact, We must submit data. To submit data, we will generate page refresh, it may be acceptable, but if it is large, it will be unbearable. Is there any way to improve it?
We know that AJAX is a very common method in Web programming. Using AJAX can effectively reduce page refreshes and get desired data updates. AJAX is an asynchronous update mechanism. In terms of implementation, XHR is a core component.
XHR is short for XMLHttpRequest. When sending a request, there are GET and POST methods, and you also need to specify the URL, which has many similarities with the Form submission method. Can this be used to interact with CGI?
CGI is short for Common Gateway Interface. In APACHE, you only need to start the CGI Module to respond to CGI. For specific configuration, see this article (http://www.jb51.net/article/37987.htm ).
The next step is related implementation. Let's first implement the HTML code, as shown below:
Description
1. The Send function is implemented by xhr. Here the GET method is used. To implement the POST method, you only need to change GET to POST.
2. test. cgi is the URL of the CGI request. The Data = Hello next to the problem is the Data of the key-value pair. It can be intercepted on the CGI end and processed accordingly.
The following is the CGI implementation code:
# Include <stdio. h> # include <stdlib. h> # include <time. h> int main (void) {time_t current; struct tm * timeinfo; char * method; char * data; time (& current); timeinfo = localtime (& current ); method = getenv ("REQUEST_METHOD"); data = getenv ("QUERY_STRING"); // This sentence must be added; otherwise, a page exception occurs during asynchronous access: printf ("Content type: text/html \ n "); printf (" Method: % s \ n Cgi receive: % s \ n Cgi back: % s ", method, data, asctime (timeinfo ));}
Description
1. method = getenv ("REQUEST_METHOD") is the GET or POST method used to obtain the xhr request. Note that getenv is the method for obtaining environment variables, and REQUEST_METHOD is the string of the key corresponding to GET or POST. This string is required.
2. data = getenv ("QUERY_STRING") is used to obtain xhr data.
3. Use printf to respond to xhr requests. Note that you need to add ("Content type: text/html \ n"). The last printf is used to respond to specific data. Here, I sent the xhr Request Method and data together with the server time to xhr.
The following is the execution result.