转载自: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")
}
)