我试图在我的 javascript 代码中针对 Geocoding API 进行地理编码。我得到定义的 url
var url = "http://http://maps.googleapis.com/maps/api/geocode/json?address=New York, Manhattan&sensor=false"
,我需要从中检索 JSON 对象。我使用的第一种方法是根据维基百科使用这样的 XmlHttpRequest
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
my_JSON_object = JSON.parse(http_request.responseText);
}
};
在触发 open() 函数后,我运行代码并在调试器中获得这样的输出:
http_request: XMLHttpRequest
onabort: null
onerror: null
onload: null
onloadend: null
onloadstart: null
onprogress: null
onreadystatechange: function () {
readyState: 1
response: ""
responseText: ""
responseType: ""
responseXML: null
status: [Exception: DOMException]
statusText: [Exception: DOMException]
upload: XMLHttpRequestUpload
withCredentials: false
__proto__: XMLHttpRequest
这意味着显然没有发生任何真正有用的事情。我的第二种方法是由于 json.org,我尝试使用 JSONRequest 进行调用
var requestNumber = JSONRequest.get(
url,
function (requestNumber, value, exception) {
if (value) {
document.write(value);
} else {
document.write(exception);
}
}
调试器告诉我 JSONRequest 没有定义!由于 json.org 它的原生 JS 对象,所以有什么问题?请注意,我在附近的脚本中使用了从谷歌正确获得的 API 密钥。
解释我的解决方案失败的原因以及如何遵守此任务的任何建议将不胜感激!