如何从javascript请求json文件
我有一个返回 json 文件的 url(我已在地址栏中输入了 url,它显示了 json 输出),但我不知道如何在 javascript 中请求 json 文件。有人可以帮助我吗? 这是代码:
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=kalutara&format=json&num_of_days=4&key=myKey' ;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
http_request.open('GET', url, true);
http_request.send(null);
http_request.onreadystatechange = function() {
if ( http_request.readyState == 4) {
if ( http_request.status == 200)
success( http_request.responseText);alert(http_request.responseText);
else if (failure)
failure( http_request.status, http_request.statusText);
}
};
谢谢!!
i have a url which returns a json file(i have typed the url in the address bar and it showed the json output) but i don't know how to request for the json file in javascript. can anybody help me?
here's the code:
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=kalutara&format=json&num_of_days=4&key=myKey' ;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
http_request.open('GET', url, true);
http_request.send(null);
http_request.onreadystatechange = function() {
if ( http_request.readyState == 4) {
if ( http_request.status == 200)
success( http_request.responseText);alert(http_request.responseText);
else if (failure)
failure( http_request.status, http_request.statusText);
}
};
Thanks !!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于你的 json 文件的样子。
例如
如果文件包含类似的内容
,那么您只需使用常规脚本标签就可以使用 json 对象。
如果文件格式为:
那么您可以读取帖子中定义的内容(使用 XMLHTTP 请求),但是然后使用 eval 函数使其在页面中可用,类似于您的 success() 方法中的以下内容:
It depends on how you json file looks like.
For e.g.
If the file contains something like
Then you can just use the regular script tag to be able to use the json object.
If the file in format:
then you can read the contents as defined in your post (Using XMLHTTP request) however then use eval function to make it available in the page something like the one below in your success() method: