我用jsonp接收数据发生了一件很奇怪的事情,jsonp数据接收成功了,但是页面马上就被重载了(返回jsonp后,又进行了一次页面的请求,请求发生在jsonp接收成功后)。
实在不知道是什么问题,也不知道该怎么调试了,哪位路过的好心人指点下迷津
以下是原代码,调试步骤在最后:
HTML代码(jsonp.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jsonp</title>
<style>
#showJsonP {
width: 500px;
height: 500px;
}
</style>
<script src="jsonp.js" type="text/javascript"></script>
</head>
<body>
<div id="showJsonP"></div>
<form action="">
<input id="urlInput" type="text" value="http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer">
<button id="sub">确定</button>
</form>
</body>
</html>
JS代码(jsonp.js)
window.onload = function() {
var btn = document.getElementById("sub");
btn.onclick = function() {
var input = document.getElementById("urlInput"),
url = input.value;
debugger;
loadJsonp(url);
}
}
function loadJsonp(url) {
var script = document.createElement('script'),
rand = Math.random().toString().substring(2, 8),
functionName = "getJsonStr" + rand;
// script.async = true;
script.src = url + "?f=json&callback=" + functionName;
window[functionName] = function(data) {
setData(data);
try {
delete window[functionName];
} catch (e) {
window[functionName] = undefined;
}
}
var head = document.getElementsByTagName('head')[0];
script.onload = function() {
script.onload = undefined;
head.removeChild(script);
};
script.onerror = function(e) {
};
head.appendChild(script);
}
function setData(dataObj) {
var div = document.getElementById("showJsonP"),
data = JSON.stringify(dataObj);
div.innerText = data;
}
以下是我调试的步骤:
1.将script标签插入到文档中后,产生了jsonp的请求
2.数据接收成功准备执行函数时,产生了页面的请求
3.成功接收到了数据,但是接收后页面也被刷新了
设置表单的属性onsubmit="return false;"