c语言处理通过ajax发起http的post请求CGI并向浏览器返会值

环境:centos 6.5

web容器:apache2.4,[<http://httpd.apache.org/docs/2.4/]

准备:

cd /usr/local/httpd-2.4.20/modules/generators  \enter

  cp mod_cgi.c /usr/local/apache/bin \enter

  ./apxs -i -a -c mod_cgi.c \enter

  cd usr/local/apache/conf/

  vim httpd.conf (找到loadModule xxxx  xxxx 的地方,在后面添加 loadModule cdg_module modules/mod_cgi.so) 

  cd ../bin \enter

  ./httpd -k restart

在/usr/local/apache/htdocs/添加 index.html

<html>
<head>
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>
    <body>
        <h1>It works!hahahahhahaha~</h1>
        <input type="button" onclick="testcgi()" value="test"/>
    </body>
     <script type = "text/javaScript">
        function testcgi(){
        $.ajax({
                type: 'POST',
                url: '../cgi-bin/cgitest.cgi', 
                data:"hello world",
                dataType: "text", 
                ContentType: "application/text; charset=utf-8",
                success: function (returnedData,status) {
                    if(status=="success"){
                        alert(returnedData);
                    }
                },
                error: function (msg) {
                    alert("访问失败:"+ msg);
                }
            });
}
    </script>
</html>

在/usr/local/apache/cgi-bin添加 cgitest.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAXLEN 1024

char* getcgidata(FILE* fp, char* requestmethod);

int main(void)
{
    char * cgistr = NULL;
    char * req_method = NULL;
    printf( "Content-type: application/text;charset=utf-8\n\n" );
    req_method = getenv("REQUEST_METHOD");
    cgistr = getcgidata(stdin, req_method);
    fprintf(stdout,"you post param is %s",cgistr);
}

char* getcgidata(FILE* fp, char* requestmethod)
{
    char* input;
    int len;
    int size = MAXLEN;
    int i = 0;

    if (!strcmp(requestmethod, "GET"))
    {
        input = getenv("QUERY_STRING");
        return input;
    }
    else if (!strcmp(requestmethod, "POST"))
    {
        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;
}

编译:gcc cgitest.c -o /cgitest.cgi

打开浏览器访问:http://192.168.10.121点击test

附上我的路径:

 

哈哈哈哈哈哈哈~大功告成,牛逼坏了~

总结:cgi可以放到./或../ 或../test/ 都行,只要不高于web服务器就行。后缀名必须是.cgi,这个与web服务器的约定有关系。

  这里所使用的是httpd,理论上是可以用tomcat,nginx,weblogic等,甚至可以用自己写的web容器,如简单的tinyhttd,共500行代码。

posted @ 2018-05-23 11:23  一梦、  阅读(4645)  评论(2编辑  收藏  举报