话说菩提祖师打了孙猴子三板子 而后悟空学会72般变化以及一身神通 对待这个问题做为面试者要思考更加深层次的意义 才更能得到承认php
实际上写的ajax 很能看出一个的水平 贴几段代码就能够看出水平的高低html
代码1:青铜水平面试
var req = new XMLHttpRequest();
req.open("get", "mockData/usersinfo.json", true);
req.send();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
var result= req.responseText;
}
}ajax
特别普通的一段原生ajax 功能也是特别的简单的功能 获取一个模拟的数据 这段代码能反应啥 你能够写出来 也能记住对吧json
代码2:白银水平url
function ajax(type, url, success) {
var req = new XMLHttpRequest();
req.open(type, url, true);
req.send();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
var result = req.responseText;
success(result);
}
}
}spa
ajax("get", "http://localhost:8055/listcount.php?search=a", function (result) {
alert(result);
});3d
上面的代码 跟代码1的功能能够说是同样 可是代码的复用性 就变得彻底不同htm
是真的blog
由于能够哪里调用就哪里调用
代码3:黄金水平
function ajax(json) {
var req = new XMLHttpRequest();
var type = json["type"];
var url = json["url"];
if (json["data"]) {
var html = "?";
for (var i in json["data"]) {
html += i + "=" + json["data"][i] + "&";
}
html = html.substring(0, html.length - 1);
url += html;
}
var success = json["success"];
req.open(type, url, true);
req.send();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
var result = req.responseText;
if (json["dataType"] == "json") {
result = JSON.parse(result);
}
success(result);
}
}
}
ajax({
type: "get",
url: "http://localhost:8055/listcount.php",
data: {search: "l"},
dataType: "json",
success: function (result) {
alert(result["count"]);
}
});
以上代码功能也是同样 可是感受更好了 是否是有一点所谓jq中使用ajax的感受了 此刻能够啦啦啦的 跳个舞了 千万不要知足
代码4:钻石水平
var $ = {
ajax: function (json) {
var req = new XMLHttpRequest();
var type = json["type"];
var url = json["url"];
if (json["data"]) {
var html = "?";
for (var i in json["data"]) {
html += i + "=" + json["data"][i] + "&";
}
html = html.substring(0, html.length - 1);
url += html;
}
var success = json["success"];
req.open(type, url, true);
req.send();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
var result = req.responseText;
if (json["dataType"] == "json") {
result = JSON.parse(result);
}
success(result);
}
}
}
}
$.ajax({
type: "get",
url: "http://localhost:8055/listcount.php",
data: {search: "l"},
dataType: "json",
success: function (result) {
alert(result["count"]);
}
});
怎么样 虽然写的是原生ajax 可是写出了jq底层代码的味道 跟jq中使用方式如出一辙 参数 回调 封装 面面俱到 水平高低 一看就知道了 本身都会写 工做确定也就会用 这才是钻石水平 还有更高级的星耀 就能够融入Promise 请求头配置等等
不要小看任意一道面试题 可能其中另有深意 体验本身的价值才能拿到更快拿到offer