XMLHttpRequest和C CGI ......只发回一个单词

时间:2015-02-21 11:31:05

标签: javascript c xmlhttprequest

我正在使用一个带有脚本的简单表单进行测试,该脚本获取文本区域的值并将其发送到“sample.cgi”,现在,“sample.cgi”应该只发回我发送的文本对他来说......但是,我只回到第一个字。 我真的找不到问题。

以下是代码:

<!DOCTYPE html>
<html>
<head>
  <script>
    function mytest() {

      var xhr = new XMLHttpRequest();

      xhr.onreadystatechange = function() {

      if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { 
      //If everything is ok show the output whit an alert
       alert("This is the server answer: " + xhr.responseText);

        }

      };
      var myText = document.getElementById("message").value;
      //Request to "sample.cgi"
      xhr.open("POST", "sample.cgi", true);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      //Sending the data
      xhr.send(myText);


    }
  </script>
</head>

<body>

  <h2>MY TEST: </h2>
  <form>
    <textarea id="message">
    </textarea>
    <button type="button" onclick="mytest()">Request data</button>
  </form>
</body>

</html>

sample.gci代码:

#include <stdio.h>


int main(void)
{
 printf("Content-Type: text/plain;\n\n");


 char myText[1000];
 //the data is sent by "POST" method, then we find it in stdin
 fscanf(stdin,"%s", myText);
 printf("%s",myText);

     return 0;
}

提前致谢

1 个答案:

答案 0 :(得分:0)

非常感谢我使用fgets解决了!我没想到“mytext”没有格式化数据。

我想问一个小问题,为什么我在更改C代码时没有得到任何结果:

int main(void)
{
 printf("Content-Type: text/plain;\n\n");

 FILE * pFile;
 pFile = fopen ("sample.txt","w");
 char myText[1000];
 fgets(myText,1000, stdin);
 fprintf(pFile, "%s\n",myText);
 printf("We stored this text: %s",myText);
 fclose(pFile);
     return 0;
}

显然“xhr.onreadystatechange”甚至没有收到发送警报的正确条件。

非常感谢你的帮助!