2011-02-17 52 views
2

我正在使用雅虎BOSS和Bing API向我的网站提供搜索功能。具体而言,我使用他们的JSON响应格式,我会将回调函数传递给搜索提供程序,稍后将使用搜索结果回调该搜索提供程序。我的回调函数实际上被调用,但问题是,如果我一次创建多个请求,我无法确定某个响应是针对哪个请求的。为此,有没有办法将带回调函数的附加参数传递给搜索提供程序,以便稍后可以使用它来确定哪个响应与哪个请求一起进行? 谢谢如何使用回调函数传递参数来搜索雅虎BOSS和BING之类的API?

回答

1

我和你有同样的问题!我GOOGLE了,并找到一些解决方案 ,我已经解决了我的问题。现在我给你看,我希望它可以帮助你:)

以前的代码:

 function MakeGeocodeRequest(credentials) { 
     var pins = checkLocation.d 
     $.each(pins, function (index, pin) { 
      var geocodeRequest = 'http://ecn.dev.virtualearth.net/REST/v1/Locations/' + pin.City + ',' + pin.Country + '?output=json&jsonp=GeocodeCallback&key=' + credentials; 
      CallRestService(geocodeRequest); 
     }); 



    function CallRestService(request) { 
     var script = document.createElement("script"); 
     script.setAttribute("type", "text/javascript"); 
     script.setAttribute("src", request); 
     document.body.appendChild(script); 
    } 

功能GeocodeCallback(结果){..做的结果回调, - >我要加入一些pin信息在这里}

因为每个sccipt添加到文档(document.body.appendChild(script);)它将运行 - >和回调,你不能添加更多的参数。

我通过AJAX请求解决其(犯规添加到文档的任何更多)中,当AJAX调用成功 - >我所说的GeocodeCallback(结果,) 下面是完整的代码。

function MakeGeocodeRequest(credentials) { 
     var pins = checkLocation.d; 
     $.each(pins, function (index, pin) { 
      $.ajax({ 
       url:"http://ecn.dev.virtualearth.net/REST/v1/Locations/", 
       dataType: "jsonp", 
       data:{key:credentials,q:pin.City + ',' + pin.Country}, 
       jsonp:"jsonp", 
       success: function(result){ 
        GeocodeCallback(result,pin); 
       } 
      }); 
     }); 
    } 
    function GeocodeCallback(result,pin) { ... to do here}