AicsKnowledgeBase_client/AicsKnowledgeBase/qml/global/Request.qml

107 lines
3.3 KiB
QML

pragma Singleton
import QtQuick
QtObject {
id: request
property string baseUrl: "https://api.hammer-hfut.tk:233/aics/main/"
property string searchUrl: "https://api.hammer-hfut.tk:233/aics/query/"
//property string baseUrl: "http://192.168.156.74:8080/"
// GET
function get(url, success, failure) {
var xhr = new XMLHttpRequest
xhr.open("GET", baseUrl + url)
xhr.onreadystatechange = function () {
handleResponse(xhr, success, failure)
}
xhr.send()
}
// GET in searchUrl
function getSearch(url, success, failure) {
var xhr = new XMLHttpRequest
xhr.open("GET", searchUrl + url)
xhr.onreadystatechange = function () {
handleResponse(xhr, success, failure)
}
xhr.send()
}
// PUT in searchUrl
function putSearch(url, arg, success, failure) {
var xhr = new XMLHttpRequest
xhr.open("PUT", searchUrl + url)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.withCredentials = true
xhr.onreadystatechange = function () {
handleResponse(xhr, success, failure)
}
xhr.send(arg)
}
function getAwait(url) {
var xhr = new XMLHttpRequest
xhr.open("GET", baseUrl + url, false)
xhr.send(null)
// wait for response then return response data
return xhr.responseText
}
// POST
function post(url, arg, success, failure) {
var xhr = new XMLHttpRequest
xhr.open("POST", baseUrl + url, true)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.withCredentials = true
xhr.onreadystatechange = function () {
handleResponse(xhr, success, failure)
}
xhr.send(arg)
}
// PUT
function put(url, arg, success, failure) {
var xhr = new XMLHttpRequest
xhr.open("PUT", baseUrl + url, true)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.withCredentials = true
xhr.onreadystatechange = function () {
handleResponse(xhr, success, failure)
}
xhr.send(arg)
}
/* function post(url, arg, success, failure) {
var xhr = new XMLHttpRequest
xhr.open("POST", baseUrl + 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) {
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)
failure(xhr.responseText, xhr.status)
}
}
}
}