无法从链接获取json数据

时间:2012-07-10 06:14:07

标签: ajax json jquery

这是我的脚本,我无法从链接中获取json数据,请解答我,指出我在哪里错了,谢谢你提前

<script type="text/javascript">
          function getsomethin()
          //wait for HTML document
          {
              alert("l");
              $.getJSON('http://developers-blog.org/resources/jquery-ajax/heroes-list.json', function (data) {
                  console.log(data);                  alert(data);
                  $.each(data, function (i, name) {
                      $("div").append(name + " ");
                  });
              });
          }       

    </script>

3 个答案:

答案 0 :(得分:0)

您必须使用JsonP进行跨域请求。

“jsonp”:使用JSONP加载JSON块。添加额外的“?callback =?”到URL的末尾以指定回调。通过将查询字符串参数“_ = [TIMESTAMP]”附加到URL来禁用缓存,除非缓存选项设置为true。

试试这个

$(document).ready(function() {
    var url =  "http://developers-blog.org/resources/jquery-ajax/heroes-list.json";
    $.getJSON(url + "?callback=?",  function(data) {
        console.log(data);                  alert(data);
                  $.each(data, function (i, name) {
                      $("div").append(name + " ");
    });
});

答案 1 :(得分:0)

如果它的跨域

你需要jsonp
$.ajax({
    url: 'http://example.com/.../file.json',
    data: 'param=3',
    dataType: 'jsonp',
    success: function(results) {
        //callback
    },
    complete: function() {
        //callback
    }
});

http://api.jquery.com/jQuery.ajax/

答案 2 :(得分:0)

我继续使用这种格式从链接获取数据,它工作,谢谢你们的支持

if (xmlHttp.readyState==4)
        {
            alert(xmlHttp.status);
            if(xmlHttp.status==200)
            {

            alert("hi");
            var jsondata=eval("("+xmlHttp.responseText+")") //retrieve result as an JavaScript object
            jsonOutput=jsondata.message.result;
            alert(jsonOutput);

            InitializeLeadStorage()

        }
        }