我已经开始学习javascript了,我在下面写了一段代码。
var dataFetch = $.getJSON("http://localhost:12345/stream", function (Data) {
alert(Data);
$.each( Data, function () {
alert(this);
$("<li>").html(this.rss).prependTo(tweetList);
});
});
dataFetch.done(function () {
alert("done");
});
dataFetch.fail(function () {
alert("fail");
});
当我将链接 http://localhost:12345/stream
放入浏览器时,我得到:
{"rss":{"version":"2.0","channel":{"title":"Dave Winer","link":"http://scripting.com/","description":"Dave Winer's \"Scripting News\" weblog, started in April 1997, bootstrapped the blogging revolution.","language":"en-us","copyright":"Copyright 2012 Scripting News, Inc.","pubDate":"Mon, 08 Oct 2012 04:00:00 GMT","lastBuildDate":"Mon, 08 Oct 2012 18:12:27....
........... much more here
但是当我运行这个 html 文件时,我得到失败,并显示失败警报对话框。
我通过 Node.js 服务器代码通过 JSON.stringify(some_json_object).
在本地主机上发送数据。
错误是什么?
最佳答案
将“Access-Control-Allow-Origin”:“*”放在createServer
函数的响应 header 中解决了问题:
response.writeHead(200, {"Content-Type" : "text/plain",
"Access-Control-Allow-Origin" : "*"});
这允许每个人访问我服务器的这个端点。也可以用 IP 地址或域名来代替 *,以仅允许特定客户端访问。
关于Javascript 和 jQuery 获取数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18306460/