2013-05-09 36 views
0

我有将Json复制到我的Jquery脚本中的问题。使用jQuery检索远程JSON内容

一个PHP脚本,通过回声一个JSON像位于http://myserver.com/script.php回报:

{"locations":[{"name":18492554,"lat":"12345","long":"234"},{"name":18492553,"lat":"4567","long":"234},{"name":18492555,"lat":"2234","long":"234}]} 

我想这一点积成我喜欢Jqueru脚本:

(function() { 
    window.onload = function() { 

     // Creating a new map 
     var map = new google.maps.Map(document.getElementById("map"), { 
      center: new google.maps.LatLng(41.6, -0.88), 
      zoom: 12, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }); 


     ///////////////////// GET the JSON data /////////////////// 
var json = // ??????? 



     // Creating a global infoWindow object that will be reused by all markers 
     var infoWindow = new google.maps.InfoWindow(); 

     // Looping through the JSON data 
     for (var i = 0, length = json.length; i < length; i++) { 

       var data = json[i], 
       latLng = new google.maps.LatLng(data.lat, data.long); 

      // Creating a marker and putting it on the map 
      //var iconBase = 'https://dea-srl.net/domenico/traking/js/'; 

      var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; 
      var marker = new google.maps.Marker({ 
       position: latLng, 
       map: map, 
       title: data.nombre, 
       icon: iconBase + 'schools_maps.png' 
       }); 

      // Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data) 
      (function(marker, data) { 

       // Attaching a click event to the current marker 
       google.maps.event.addListener(marker, "click", function(e) { 
        infoWindow.setContent(data.nombre); 
        infoWindow.open(map, marker); 
       }); 


      })(marker, data); 

     } 

    } 

})(); 

我的问题是拿到的Json进入de jquery。有可能的?

我tryed使用get类似方法具:

$.get(" http://myserver.com/script.php"); 

但它不工作。

对此有何想法?提前致谢。

+0

你是什么意思“它不起作用?”怎么了?你有错误吗? – 2013-05-09 22:10:49

+0

我不知道如何调试,但我尝试后放置analert,警报(json),并没有显示。我怎样才能得到一个错误? – doxsi 2013-05-09 22:15:44

+0

是http://myserver.com是你脚本的同一个域名吗? – 2013-05-09 22:16:20

回答

1

你的意思是不工作?你有什么错误?

您是否在使用done功能?

$.get(" http://myserver.com/script.php").done(function(data) { 
    console.log(data); 
}); 

或者您可以直接使用$.getJSON函数。

+0

您的程序块的consolo放置:ReferenceError:$未定义 $ .get(“http://myserver.com/script.php").done(function(data){ – doxsi 2013-05-09 22:21:42

+0

添加库解决错误 – doxsi 2013-05-09 22:26:07

+1

那么,你试图使用jquery而不包括它吗? – 2013-05-09 22:27:08

1
$.getJSON('http://myserver.com/script.php', function(data) { 
    var json = data; 
}); 

加载json数据。 如果还有其他问题,你会更精确一点。