如何用一个简单的函数(没有Ajax,没有jQuery)访问其他主页的数据



我想用一个简单的函数访问此链接返回的数据:https://geoapi123.appspot.com/

如果你点击链接,返回的结果看起来像:

function geoip_country_code(){return"UK"}
function geoip_country_name(){return"United Kingdom"}
function geoip_city(){return"London"}
...

特别是,我正在寻找geoap_city。我不想使用AJAX或jQuery。我需要一个简单的函数,它不需要脚本标记或头中的任何引用。接收到的数据需要存储在一个变量中,完全独立于主页或主页上的任何事件。该函数不能被任何加载或点击事件调用,也不能被主页上发生的任何其他事件调用。

下面是一个使用headscript标记的工作示例(不是我想要的(:

<head>
<script language="JavaScript" src="https://geoapi123.appspot.com/"></script>
</head>
<body>
<script language="JavaScript">
var city = geoip_city();
alert(city);
</script>
</body>

以下是我想要的想法

function getLocation() {
???                            //access homepage somehow here
var city = geoip_city();       //get result
alert(city);                   //alert result
};
getLocation();                     //call function

这是我迄今为止最接近的尝试(不起作用,返回为"0"(:

function accessLocation() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", "https://geoapi123.appspot.com", true);
xmlhttp.send();
};
accessLocation();

您可以通过代码添加脚本元素,并从"geoapi"加载源代码:

function clickHandler() {
var city = geoip_city();
alert(city);
}
function ready() {
var element = document.getElementById('cityFinder');
element.addEventListener('click', clickHandler, false);
}
function init() {
var script = document.createElement('script');
script.onload = function() {
ready();
};
script.src = "https://geoapi123.appspot.com/";
document.getElementsByTagName('head')[0].appendChild(script);
}
<body onload="init();">

<input type="button" id="cityFinder" value="Where am I?"></input>
</body>

最新更新