2012-01-09 107 views
6

最近我正在使用Qt-Qml的諾基亞手機。我必須向給定的HTTPS Url發送POST請求。 我正在使用QML,我試圖在沒有任何運氣的情況下使用Javascript。Https POST/GET與Qml/Qt

任何人都有一個想法嗎?可以在QML中使用Javascript來完成它? 任何建議如何使它在QT?

我打過電話這樣的功能:

var http = new XMLHttpRequest() 
var url = "myform.xsl_submit"; 
var params = "num=22&num2=333"; 
http.open("POST", url, true); 

//Send the proper header information along with the request 
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
http.setRequestHeader("Content-length", params.length); 
http.setRequestHeader("Connection", "close"); 

http.onreadystatechange = function() {//Call a function when the state changes. 
    if(http.readyState == 4 && http.status == 200) { 
     print("ok"); 
    }else{ 
       print("cannot connect"); 
     } 
} 
http.send(params); 
+1

'XMLHttpRequest.DONE'是很容易,'4'記,我猜... – 2015-08-17 19:30:12

回答

4

if說法錯誤的是:該函數被調用好幾次,但只有一次http.readyState = 4。因此,儘管沒有錯誤,但您仍然可以打印錯誤消息。

您應該首先檢查是否http.readyState = 4,然後查看狀態碼。

這裏是一個最小的工作例如:

import QtQuick 1.1 

Rectangle { 
    Component.onCompleted: { 
     var http = new XMLHttpRequest() 
     var url = "http://localhost:8080"; 
     var params = "num=22&num2=333"; 
     http.open("POST", url, true); 

     // Send the proper header information along with the request 
     http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     http.setRequestHeader("Content-length", params.length); 
     http.setRequestHeader("Connection", "close"); 

     http.onreadystatechange = function() { // Call a function when the state changes. 
        if (http.readyState == 4) { 
         if (http.status == 200) { 
          console.log("ok") 
         } else { 
          console.log("error: " + http.status) 
         } 
        } 
       } 
     http.send(params); 
    } 
} 

我創建了一個本地的僞Web服務器與netcat來測試它:

% echo -e 'HTTP/1.1 200 OK\n\n' | nc -l 8080 
POST/HTTP/1.1 
Content-Type: application/x-www-form-urlencoded;charset=UTF-8 
Content-Length: 15 
Connection: Keep-Alive 
Accept-Encoding: gzip 
Accept-Language: de-DE,en,* 
User-Agent: Mozilla/5.0 
Host: localhost:8080 

num=22&num2=333 
+0

是的,其實我把 「var url =」https:// .....「;」它只是一個例子.. – fran 2012-01-11 08:54:07

+0

@fran哦,確定:)但我發現了一些東西不同的,這可能會導致錯誤信息,... – hiddenbit 2012-01-11 09:55:42

+0

是的,你是對的!無論如何謝謝你..仍然掙扎着做請求..但沒辦法 – fran 2012-01-11 12:44:41