Search code examples
javascriptexecutionsrc

How can I call this script from a button click


I'd like the following script to execute as the result of a button click()

<script src="https://www.googleapis.com/buzz/v1/activities/search?callback=handler&alt=json&q=ruby&max-results=100"></script>

All client side code; html & javascript. I'm calling a javascript function on the button click and tried using document.write() to write out the above, but I can't get the script to execute.

Or, maybe the code is executing, but its not reaching the callback=handler.

I do almost all server side coding (asp.net) and I'm a little lost in the javascript/client side of things.


Solution

  • The handler should be the name of a client-side function that will receive the data. You should also add a click event handler to the button and use AJAX to retrieve the results. Here's how you would do it using jQuery (which I recommend). Note using jQuery you can pass the name of the handler as ? and it will construct a handler for you using the anonymous function you supply.

    <script type="text/javascript">
       $(function() { // execute on document ready
           $('#ButtonID').click( function() { // add the click event handler to button
              $.getJSON( 'https://www.googleapis.com/buzz/v1/activities/search?callback=?&alt=json&q=ruby&max-results=100', function(result) {
                    // do something with the result
              });
           });
       });
    </script>