2013-02-13 45 views
2
(function($) {     

    function CleanQueryString(query) 
    { 
     return encodeURI(query); 
    }; 

    function ConcatData(settings) 
    {        
     settings.concatUrl = settings.googleUrl; 
     settings.concatUrl = settings.concatUrl.replace("{key}", settings.googleApiKey); 
     settings.concatUrl = settings.concatUrl.replace("{country}", settings.country);  
     settings.concatUrl = settings.concatUrl.replace("{query}", settings.cleanQuery); 
    }; 

    $.fn.GoogleSearchResult = function(options) { 

     var settings = $.extend({ 
      query: null, 
      googleApiKey: "myapikey", 
      googleUrl: "https://www.googleapis.com/shopping/search/v1/public/products?key={key}&country={country}&q={query}&alt=json", 
      concatUrl: "", 
      country: "UK", 
      cleanQuery: "" 
     }, options); 

     return this.each(function() { 
      if(settings.query) 
      { 
       var $t = $(this); 

       settings.cleanQuery = CleanQueryString(settings.query); 
       ConcatData(settings);  
       alert(settings.concatUrl); // This alerts the correct url and I've checked that it returns json 

       $.getJSON(settings.concatUrl, function(data) { 
        alert("hi"); // This never alerts      
        $t.html(data);     
       }); 
      } 

      return false;  
     });  
    }; 
})(jQuery); 

我不能让我的$ .getJSON工作..任何想法,为什么这可能不会返回任何东西:jQuery插件无法得到的getJSON工作

https://developers.google.com/shopping-search/v1/getting_started

我送返回的网址正确的数据,当我直接去它。

+0

您是否试图在不同的服务器上访问JSON?如果是这样,您需要使用某种服务器端脚本将其加载到自己的服务器上,并使用'.getJSON'访问*。 [Google购物搜索似乎没有提供JSON-P](https://developers.google.com/shopping-search/v1/getting_started) – Blazemonger 2013-02-13 14:24:16

+0

链'.error(function(xhr,status,error){alert( “错误:”+状态+“”+错误);})'在它上面,看看错误信息是什么 – nbrooks 2013-02-13 14:25:13

+0

是的,即时通讯使用谷歌搜索结果API来获得结果:https://developers.google。 com/shopping-search/v1/getting_started – Jimmyt1988 2013-02-13 14:25:32

回答

1

您是否试图访问不同服务器上的JSON?如果是这样,您需要使用某种服务器端脚本将其加载到自己的服务器上,并使用.getJSON访问它。 Google Shopping Search doesn't appear to offer JSON-P

如果你可以写一个PHP页面或一些其他的服务器端语言,it's trivial to get and return the external JSON,现在将是你自己服务器上,并且可以使用.getJSON很容易地加载。

+0

它支持JSONP,虽然它没有在该页面上说过。 – nbrooks 2013-02-13 14:36:26

+0

jQuery.support.cors = true;这是答案 – Jimmyt1988 2013-02-13 14:37:05

0
jQuery.support.cors = true; 
$.getJSON(settings.concatUrl, function(data) { 
    alert(data);      
    $t.html(data);     
}).error(function(xhr, status, error) { alert("error" + status +" " + error); }) ; 

Jquery跨域支持可以使用此设置启用。

0

您需要使用JSONP从外部源传输数据。在谷歌API支持这一点,所以在你的代码而言,这是作为附加&callback=xyz到您的网址,其中xyz是一些功能,外部服务器将包裹在你的代码一样简单。

https://www.googleapis.com/shopping/search/v1/public/products?key={key}&country={country}&q={query}&alt=json&callback=xyz

jQuery将自动查找一个名为?的回调,因此您可以使用callback=?或通过将jsonp: xyz添加到您的AJAX请求参数来指定自定义名称。