通过typeScript的属性接口封装ajax

jq的ajax调用:



$.ajax({
type: "GET",
url: "obj.json",
data: {"id": $("#id").val(), "name": $("#name").val},
dataType: "json"
});


 使用type编辑,封装ajax



// 定义接口
interface Config{
type:string; // 接口使用分号;
url:string;
data?:string;
dataType:string
}

function ajax(config:Config, callback:(data:string)=>void){
var xhr = new XMLHttpRequest();
xhr.open(config.type , config.url, true);
xhr.send(config.data);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
if(config.dataType == 'json') {
callback(JSON.parse(xhr.responseText));
} else {
callback(xhr.responseText);
}
}
}
}
// 调用ajax
ajax({
type: "GET",
url: "obj.json",
dataType: "json"
}, function(data) {
console.log(data);
});


 浏览器上执行结果:

TypeScript学习: 八、TypeScript的属性接口用法封装ajax_TypeScript