原文参照:https://blog.csdn.net/zxcvn8866/article/details/52179709
返回JSON格式数据:
{"list1":[{"item":"0审计管理"},{"item":"1菜单管理"},{"item":"2订单管理"},{"item":"3合同管理"},{"item":"4物流管理"},{"item":"5行政管理"},{"item":"6人事管理"},{"item":"7购物管理"},{"item":"8批发管理"},{"item":"9安全管理"},{"item":"10账号管理"},[{"item":"11财务管理"}],{"item":"12其他管理"}],"list2":[{"key":"value001"},{"key":"value002"}],"list3":5555,"list4":{"key401":"val401","key402":"val402","key403":[{"key501":"val501","key502":"val502"},{"key601":"val602","key602":"val602"}]},"广西":{"南宁市":["青秀区","江南区","兴宁区","良庆区","邕宁区","西乡塘区","武鸣区"]},"dataCreater":"phpServer","dataCreateTime":"2018-06-02 18:41:34"}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>原生js通过jsonp请求json数据</title>
</head>
<body>
<p>原生js通过jsonp方式请求json数据实现跨域请求</p>
<input type="text" id="url0" value="http://192.168.2.200:8080/jsonpserver.php?jsonpCallBack=myFeedBack" size="60"/>
<input type="button" value="内网请求测试" οnclick="callJsonpServer(0)"/><br>
<input type="text" id="url1" value="http://www.link2world.top/jsonpserver.php?jsonpCallBack=myFeedBack" size="60"/>
<input type="button" value="外网请求测试" οnclick="callJsonpServer(1)"/><br>
<div id="result"></div>
<script>
function callJsonpServer(arg){
var url=document.getElementById("url"+arg).value;
var oldScript=document.getElementById("jsonpScript");
alert("url= "+url+"\n"+"oldScript= "+oldScript);
if(oldScript){
alert("Remove old script ...");
document.body.removeChild(oldScript);//移除原来的,再添加一个新的,才能再次触发数据请求动作并执行myFeedBack(data)函数
}
alert("Add a new script");
var newScript=document.createElement("script");
newScript.setAttribute("type","text/javascript");
newScript.setAttribute("src",url);
newScript.setAttribute("id","jsonpScript");
document.body.appendChild(newScript);
alert("Append the script to body ok");
}
function myFeedBack(data){
alert("Got datas and to process...");
var resultZone=document.getElementById("result");
var results="";
for(var i in data){
results+=i+" : "+data[i]+"\n";
}
resultZone.innerText=results;
}
</script>
</body>
</html>