[英]Requesting JSON from server and parsing in Javascript
I am trying to pull json down from my server and parse it into a Javascript object. 我正在尝试从服务器中提取json并将其解析为Javascript对象。 here is what my json looks like:
这是我的json的样子:
{
"tour1": [
{
"title": "building1",
"description": "Tour of building1",
"image": "Icon.png",
"video": "tour.mp4",
"length": "0.00",
"version": "1.0",
"timestamp": "1111111111"
}
]
}
Here is the requst to the server: 这是服务器的要求:
<!DOCTYPE html>
<html>
<body>
<h2>Parse JSON from Server</h2>
<p id="demo"></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
$.ajax({
url: "mysite.com/videos/tour.json";
var j = [];
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
});
window.alert(j.tour1[0].title);
</script>
</body>
</html>
I cant understand why its not working. 我不明白为什么它不起作用。 I am new to javascript.
我是javascript新手。 I appreciate any help with this issue.
感谢您提供有关此问题的帮助。
I think better if you use getJson when you want to load JSON-encoded data from the server using a GET HTTP request, check example bellow : 我想如果要使用GET HTTP请求从服务器加载JSON编码的数据时使用getJson更好,请查看以下示例:
$.getJSON( "mysite.com/videos/tour.json", function( j ) {
alert( j.tour1[0].title );
});
Hope this helps. 希望这可以帮助。
Ajax call is an asynchronous call, j is not populated as soon as your ajax statement ends. Ajax调用是一个异步调用,一旦您的ajax语句结束,就不会填充j。
Use success handler of Ajax to alert the j (didn't tested the code) 使用Ajax的成功处理程序来警告j(未测试代码)
$.ajax({
url: "mysite.com/videos/tour.json",
method: "GET",
dataType: "JSON",
success: function( data ){
window.alert(data.tour1[0].title);
}
});
gurvinder give the best solution, because if you are firing the ajax-request then you must catch the response, but if you make the alert in your code your request is still working and j must be undefined because it is not a global variable. gurvinder提供了最佳解决方案,因为如果您触发ajax请求,那么您必须捕获响应,但是如果您在代码中发出警报,则您的请求仍然有效,并且j必须是未定义的,因为它不是全局变量。 there a lot of mistakes:
有很多错误:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.