这是我的代码,它将发送获取请求并以 html 格式呈现响应的一些内容。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mytitle</title>
</head>
<body>
<script type="text/javascript">
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.send();
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
</script>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
<div id="placeholder"></div>
</body>
</html>
当我在 Eclipse 浏览器中运行时,这段代码运行良好。但它在浏览器中失败。 我已经检查了浏览器配置以启用脚本并启用它。浏览器配置也没有问题。
我是 javascript http 请求的新手。 请建议
最佳答案
我在某处读到 Eclipse 浏览器不遵守 same origin policy [Wikipedia] .这就是为什么可以向外部 URL 发出 Ajax 请求,这在“普通”浏览器中默认是不可能的。
事实上,如果我尝试 run your code [jsFiddle] ,我收到以下错误:
XMLHttpRequest cannot load
http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json
. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin'http://fiddle.jshell.net'
is therefore not allowed access.
有multiple ways to work around the same-origin policy [SO] .在您的情况下,该服务似乎支持 JSONP [SO] .
使用 JSONP,您不会对服务器进行 Ajax 调用,而是使用带有动态创建的脚本元素的 URL。脚本元素不受同源策略的限制,因此可以从其他服务器加载数据(代码)。
服务器将返回一个包含单个函数调用的 JavaScript 文件。函数的名称由您通过查询参数指定。所以,如果 JSON 响应通常是:
{"message":"accurate","cod":"200", ...}
通过向 URL 添加参数 callback=foo
,服务器返回
foo({"message":"accurate","cod":"200", ...});
(关注 this URL 查看您的服务示例)
此响应可以作为 JavaScript 进行评估。 请注意,您不能不将每个 JSON 响应转换为 JSONP。服务器必须支持 JSONP。
这是一个完整的例子:
// this function must be global since the script is executed in global scope
function processResponse(obj1) {
document.getElementById("placeholder").innerHTML =
obj1.message + " " + obj1.list[0].name;
}
function httpGet() {
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
// the following line is just to explictly show the `callback` parameter
url += '&callback=processResponse';
// ^^^^^^^^^^^^^^^ name of our function
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
如果你用 google 搜索 JSONP,你会发现 more information [Wikipedia]和教程。
关于javascript 代码在浏览器中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20367566/