How can I pass parameters with callback functions to search APIs like Yahoo BOSS and BING?

801 views Asked by At

I am using Yahoo BOSS and Bing APIs to provide search functionality to my site. Specificaly, I use their JSON response formats where I would pass a callback function to the search provider that would later be called back with the search results. My callback function actually gets called, but the problem is, if I make more than one requests at a time, I can't tell which request a certain response is for. To this end, is there a way to pass additional parameters with the callback function to the search provider so that I can later use it to identify which response goes with which request? Thank you

1

There are 1 answers

0
chithanh_12 On

I have a same problem with you! I googled and find some solutions and I has solve my problem. Now i show it to you, I hope it can help you :)

Previous code:

       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);
    }

function GeocodeCallback(result) {.. to do with result callback, --> i want to add some pin infomation here}

Because each sccipt when add to document ( document.body.appendChild(script);) it will be run --> and callback, you cant add more params.

I solve it by request through ajax (doesnt add to document any more), when the ajax call success --> I call the GeocodeCallback(result, pin) Here is the complete code.

   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}