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

浏览器端关键代码:

<input type="button" onclick="testcgi()" value="test">
function testcgi(){
    $.ajax({
                type: 'POST',
                url: '../cgi-bin/cgitest.cgi', 
                data:"hello world",
                dataType: "text", 
                ContentType: "application/json; charset=utf-8",
                success: function (returnedData,status) {
                    if(status=="success"){
                        alert(returnedData);
                    }
                },
                error: function (msg) {
                    alert("访问失败:"+ msg);
                }
            });
}

后端cgi代码:

#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/json\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 ../cgi-bin/cgitest.cgi

点击test后前端alert出:you post param is hello world

总结:

猜你喜欢

转载自www.cnblogs.com/airduce/p/9075972.html
今日推荐