2013-05-09 108 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數據。 如果還有其他問題,你會更精確一點。