2016-09-21 32 views
0

我有ajax XMLHttpRequest的HTML頁面來訪問C++ .cgi文件。我將HTML中的值傳遞給.cgi,並且我需要返回「成功」或「失敗」的消息。這是我的目標。如何使用XMLHttpRequest ajax從cgi Cpp將值返回到HTML?

我的HTML代碼:

<!DOCTYPE html> 
<html> 
<head> 

<script type = "text/javascript"> 

var XMLHttp; 

if(navigator.appName == "Microsoft Internet Explorer") { 
     XMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); 

} else { 
     XMLHttp = new XMLHttpRequest(); 
} 


function getresponse() { 

    var fanme = document.getElementById('fname').value ; 

    var postData; 

    postData += fname; 

    XMLHttp.open("POST", "ajaxtry.cgi", true); 

    XMLHttp.onreadystatechange = function() { 
     document.getElementById('response_area').innerHTML = XMLHttp.responseText; 
    } 

    // Set the appropriate HTTP request headers 
     XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     XMLHttp.setRequestHeader("Content-length", postData.length); 

     // Make request 
     XMLHttp.send(postData); 



} 
</script> 

<h1>Sample application</h1> 

    First Names(s)<input onkeyup = "javascript: getresponse()" id="fname"> 

<div id = "response_area"> 
</div> 


</body> 
</html> 

和CPP的CGI文件:

#include <unistd.h> 
#include <iostream> 
#include <vector> 
#include <string> 

#include "cgicc/Cgicc.h" 
#include "cgicc/HTTPHTMLHeader.h" 
#include "cgicc/HTMLClasses.h" 

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

using namespace std; 
using namespace cgicc; 

int main(int argc, char **argv) 
{ 

    Cgicc cgi; 

    try { 

     form_iterator fname = cgi.getElement("fname"); 
     form_iterator sname = cgi.getElement("sname"); 

      if(null != **fname) 
      { 
      cout<<"sucess"; 
      } 
      else 
      cout<<"failed"; 

     } 
     catch(exception& e) { } 

    return 0 ; 

} 

我得到的輸出,如:一些編碼值:

ELF>�@@@[email protected] @ @@@@@��[email protected]@@@�� ��`�`�@ ��`�`[email protected]@DDP�td��@�@LLQ�tdR�td��`�`((/lib64/ld-linux-x86-64.so.2GNU GNUMh���N��N틟����~��0!P 

,爲什麼我不能得到成功或失敗的消息回到div的內部HTML?有什麼遺漏?有什麼建議麼 ?

回答

1

您得到的輸出似乎是您的C代碼本身的編譯二進制文件。

您需要將服務器配置爲才能執行程序並返回響應而不是將其作爲靜態文件提供。

一般情況下,你需要沿着線的東西:

<Directory "/usr/local/apache2/htdocs/somedir"> 
    Options +ExecCGI 
    AddHandler cgi-script .cgi 
</Directory> 

一個detailed guide is in the manual

+0

謝謝..我正在工作 – user2986042