如何从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 !!
这取决于你的 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: