【问题标题】:QUERY_STRING is not obtained in CGI (C code)QUERY_STRING 未在 CGI 中获得(C 代码)
【发布时间】:2015-06-11 08:56:01
【问题描述】:

我正在使用 lighttpd 服务器。并尝试用 C 编写示例 CGI 并将 HTML 返回到服务器。 我对 CGI 的 ajax 调用是

    <head>
            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <title>Watch TV</title>
            <script src="js/jquery.js"></script>
            <script type="text/javascript">
            function myTest(){
                    $.ajax({
        type: 'GET',
        url: "http://10.47.5.158:50080/htmldiag/cgi-bin/test.cgi",
        async: true,
        data: {'m':2, 'n':3},
        dataType: "html",

        success: function(data) {
            console.log("Entered success case------------------------", data);
        },
        error: (function(msg, url, ln) {
            console.log("Entered error case------------------------", msg, url, ln);
        })
    });
            }
            </script>
    </head>

我的 CGI 是

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *data;
long m,n;
printf("%s%c%c\n",
"Content-Type:text/html",13,10);
printf("Access-Control-Allow-Origin: *");
printf("<!DOCTYPE html><html>\n");
printf("<HEAD><TITLE>Multiplication results</TITLE></HEAD>\n");
printf("<BODY><H3>Multiplication results</H3>\n");
data = getenv("QUERY_STRING");
if(data == NULL)
  printf("<P>Error! Error in passing data from form to script.");
else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2)
  printf("<P>Error! Invalid data. Data must be numeric.");
else
  printf("<P>The product of %ld and %ld is %ld.",m,n,m*n);
printf("</BODY></HTML>\n");
return 0;
}

我也尝试过从 URL 提供参数。我无法获取 QUERY_STRING,或获取 HTML 格式的响应。我得到的只是它在成功案例中输入的日志和控制台中的整个 cgi 文件。

【问题讨论】:

  • CGI?在 C?没有任何库处理查询字符串解析等?你喜欢痛苦,不是吗? ;)
  • 用C写的CGI有什么问题??

标签: html c ajax cgi lighttpd


【解决方案1】:

真的很简单,

环境变量 QUERY_STRING 设置为查询字符串。 您可以通过此调用获取它:

char *query = getenv("QUERY_STRING");

注意 getenv 的手册页并注意返回的字符串 可以静态分配。 (不要犹豫,使用 strdup 和免费)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 2011-04-24
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    相关资源
    最近更新 更多