有朋友在后台问我,说他不懂后端开发、JAVA、PHP、C#、python的话,只会一点JS,但是现在想查询多家快递的物流轨迹,手动查又不太可能实现,自己JS又只会一点点,为此烦恼了很久。
这期内容就教你:如何通过JS调用快递鸟API接口,来实现600多家的物流轨迹查询。
首先,先注册一个账号:点击注册
然后,新建一个Text文本,把下面这段代码复制进去,替换你自己的快递鸟ID和APIkey, 将txt后缀改成HTML,用浏览器预览就可以看到效果。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>JS调用快递鸟API接口</title>
<meta charset="utf-8" />
<script src="/base64.js"></script>
<script src="/md5.js"></script>
<script src="/jquery.json-2.2.min.js"></script>
<script src="/common.js"></script>
<script type="text/javascript">
function GetAPI() {
var key="快递鸟API Key";
var id = "快递鸟注册ID号";
var requestData="{'OrderCode':'','ShipperCode':'ZTO','LogisticCode':'78120038107849'}";
//MD5加密
var md5str = md5(requestData + key).toLowerCase();
//base64
var dataSign = Base64.encode(md5str);
//拼接字符串(快递鸟请求报文格式)url编码
var reqData = "RequestData=" + escape(requestData) + "&EBusinessID=" + id + "&RequestType=1002&DataSign=" + escape(dataSign) + "&DataType=2";
//reqData = "RequestData=%7b%27OrderCode%27%3a%27%27%2c%27ShipperCode%27%3a%27ZTO%27%2c%27LogisticCode%27%3a%2778120038107849%27%7d&EBusinessID=1264783&RequestType=1002&DataSign=NzMxNTAzZWYxYTJiOGIyMDhiNTVjMTc4MDQ0NjdlZDg%3d&DataType=2";
//调用
SubmitPost({
method: 'post',
url: '/api/dist',
data: reqData,
beforeSend: function (xhr) {
//调用前触发,如加载效果等
},
success: function (data, status) {
if (status) {
document.getElementById("msg").innerHTML = "";
for (var i = 0,
len = data.Traces.length; i < len; i++) {
var acceptTime = data.Traces[i].AcceptTime;
var acceptStation = data.Traces[i].AcceptStation;
//页面展示效果自己开发,这里只实现功能
document.getElementById("msg").innerHTML += acceptTime + " " + acceptStation+"<br/>";
}
}
},
error: function (data, status, e) {
if (data.status == "401") {
alert(data.status);
return;
}
}
});
}
</script>
</head>
<body>
<input id="Button1" onclick="GetAPI();" type="button" value="JS调用快递鸟API接口" />
<div id="msg"></div>
</body>
</html>
运行效果如下:
注意:
<script src="/base64.js"></script>
<script src="/md5.js"></script>
<script src="/jquery.json-2.2.min.js"></script>
这3个JS文件引用,网上都能下载到,都是通用的JS,如果有更好的建议,欢迎下方留言一起探讨。