2012-10-12 61 views
1

我用C++編寫了一個cgi腳本來將查詢字符串返回給請求的ajax對象。 我還將查詢字符串寫入文件以查看cgi腳本是否正常工作。 但是,當我要求在HTML文檔中的迴應文本顯示在一個消息框中我收到一條空白消息。從XMLHttpRequest對象獲取responseText

這裏是我的代碼:

JS:

<script type = "text/javascript"> 

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

function getresponse() { 
XMLHttp.open 
("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" + 
document.getElementById('fname').value + "&sname=" + 
document.getElementById('sname').value,true); 
XMLHttp.send(null); 
} 

XMLHttp.onreadystatechange=function(){ 
if(XMLHttp.readyState == 4) 
{ 
document.getElementById('response_area').innerHTML += XMLHttp.readyState; 
var x= XMLHttp.responseText 
alert(x) 
} 
} 
</script> 

First Names(s)<input onkeydown = "javascript: getresponse()" 
id="fname" name="name"> <br> 

Surname<input onkeydown = "javascript: getresponse();" id="sname"> 

<div id = "response_area"> 

</div> 

C++:

int main() { 

QFile log("log.txt"); 
if(!log.open(QIODevice::WriteOnly | QIODevice::Text)) 
{ 
    return 1; 
} 
QTextStream outLog(&log); 
QString QUERY_STRING= getenv("QUERY_STRING"); 

//if(QUERY_STRING!=NULL) 
//{ 

    cout<<"Content-type: text/plain\n\n" 
     <<"The Query String is: " 
     << QUERY_STRING.toStdString()<< "\n"; 
    outLog<<"Content-type: text/plain\n\n" 
      <<"The Query String is: " 
      <<QUERY_STRING<<endl; 

//} 

return 0; 
} 

我很高興幾乎所有的意見做什麼!

編輯:輸出到我的日誌文件工作的很好:

Content-type: text/plain 

The Query String is: fname=hello&sname=world 

我只注意到,如果我用IE8打開它我得到的查詢字符串。但只有在第一次「keydown」之後,IE纔會無所作爲。

回答

1

我的問題無關的代碼... 我在本地IIS7測試我的劇本,我用雙CL打開HTML頁舔文件。但是您必須通過瀏覽器(localhost/mypage.htm)打開網頁,否則對於瀏覽器而言,html和可執行文件具有不同的來源。這是不允許的。

2
  1. 您不必在on___處理程序使用javascript:,只是onkeydown="getresponse();"就夠了;

  2. IE> = 7支持XMLHttpRequest對象,因此直接檢查XMLHttpRequest是否存在比檢查導航器是否爲IE好。例如:

    if(XMLHttpRequest) XMLHttp=new XMLHttpRequest(); 
    else if(window.ActiveXObject) XMLHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    
  3. getresponse()函數中,儘量在開始下面的代碼添加(open前):

    try{XMLHTTP.abort();}catch(e){} 
    

    由於您使用的是全局對象,你可能會想「接近「它在打開另一個連接之前。


編輯

有些瀏覽器(?也許火狐本身)不辦理非 「文本/ xml」 的反應相當不錯,在默認狀態,所以要保證的東西和東西,試試這個:

function getresponse() { 
    try{XMLHttp.abort();}catch(e){} 
    XMLHttp.open("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" + 
    document.getElementById('fname').value + "&sname=" + 
    document.getElementById('sname').value,true); 
    if(XMLHttp.overrideMimeType) XMLHttp.overrideMimeType("text/plain"); 
    XMLHttp.send(null); 
} 
+0

感謝您的輸入!我做了改變。但我仍然有同樣的問題。 IE8給我返回查詢字符串。但FF只是打開一個空白的消息框。你知道這可能來自哪裏嗎? – samoncode

+0

@ Sammy46那麼現在IE在每個按鍵上都獲得文本嗎? – Passerby

+0

是的!它實際上是獲取每個鍵上的文字。但我真的很想知道當我使用FF(版本10.0.7,如果這可以幫助?) – samoncode