【QT】QT的学习:在QML中使用AJAX向某服务器发送请求获取数据

转载自:https://blog.csdn.net/keysking/article/details/79920597

(1)准备Ajax.js

// GET
function get(url, success, failure)
{
    var xhr = new XMLHttpRequest;
    xhr.open("GET", url);
    xhr.onreadystatechange = function() {
        handleResponse(xhr, success, failure);
    }
    xhr.send();
}

// POST
function post(url, arg, success, failure)
{
    var xhr = new XMLHttpRequest;
    xhr.open("POST", url);
    xhr.setRequestHeader("Content-Length", arg.length);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");  //用POST的时候一定要有这句
    xhr.onreadystatechange = function() {
        handleResponse(xhr, success, failure);
    }
    xhr.send(arg);
}



// 处理返回值
function handleResponse(xhr, success, failure){
    if (xhr.readyState == XMLHttpRequest.DONE) {
        console.log("readyState", xhr.readyState, xhr.status)
        if (xhr.status ==  200){
            if (success != null && success != undefined)
            {
                var result = xhr.responseText;
                try{
                    success(result, JSON.parse(result));
                }catch(e){
                    success(result, {});
                }
            }
        }
        else{
            if (failure != null && failure != undefined)
                console.log("error status",  xhr.responseText, xhr.status)
                failure(xhr.responseText, xhr.status);
        }
    }
}

/*将json对象转成字符串*/
function urlQuery(jsonObject) {
    var query = "";
    var i = 0;
    for(var iter in jsonObject) {

        if(i>0) {
            query += "&";
        }
        if (Array.isArray(jsonObject[iter]))
        {
            query += iter +"=" + "[" +encodeURI(jsonObject[iter]) + "]";
        }
        else
        {
            query += iter +"=" + encodeURI(jsonObject[iter]);
        }

        //console.log("item1", iter,query)
        i++;
    }
    //console.log("url query:", query);
    return query;
}

(2)在qml中调用ajax:

import "qrc:/files/resource/file/Ajax.js" as Ajax

var positionPar = {
            "expoint": [180, 500],
            "exyaw": 90,
            "type": 000}
Ajax.post("http://XXXXXX", Ajax.urlQuery(positionPar),
                  function(result, json){         //成功后的回调函数
                        console.log(result)     //结果
                        console.log(json)       //结果的Json
                  },function (){              //失败后的回调函数
                        console.log("error")
                    }
        )

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值