Search code examples
javascriptjqueryjsonp

Implementing JSONP function


I am using JSONP my goal is simple the data returned must display in my div. The code currently does not display anything. I've also integrated jquery.jsonp.js within my project my path:

                 PRJFOLDER->WEBPages->JavaScript->query.jsonp.js

the index.html file is in the path:

                  PRJFOLDER->WEBPages->index.html

My Code:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script type="text/javascript" src="http://www.jquery4u.com/function-demos/js/jquery-1.6.4.min.js"></script>
        <script>
          function getData(url, data, callback) {
             $.ajax({
              url : url,
              type : 'post',
              jsonp: "callback", // Needed for jsonp
              dataType: "jsonp", // Also needed for jsonp
              timeout : timeout,
              data : data || {},
              success : function(data) {
               callback(data);
              } // Omitted failure for this example
            });
            }
        </script>

    </head>
    <body>
        <h1>Hello World!</h1>
        <script>
                var data = {};
                var url = 'http://feeds.delicious.com/v2/json/popular?callback=?'

                getData(url, {}, function(result) {
                console.log(result);
                data = result;
                });

                $('#post-result').append(JSON.stringify(data));
        </script>

       <div id='post-result'></div>
    </body>
</html>

Can anyone please assist me in displaying the output


Solution

  • First, remove jsonp. There is no need for that. Now remember that when you are using jsonp, the server will send a function as a return value instead of an object.

    Luckily, jquery has support for jsonp and will give an object literal as the value. Just make sure beforehand that your api url supports jsonp.

    See the code below :

    function getData(url, data, callback) {
     $.ajax({
      url : url,
      type : 'post',
      jsonp: "callback", // Needed for jsonp
      dataType: "jsonp", // Also needed for jsonp
      timeout : timeout,
      data : data || {},
      success : function(data) {
       callback(data);
      } // Omitted failure for this example
    });
    

    After this, you will need to make a function to receive the value :

    var data = {};
    var url = 'http://feeds.delicious.com/v2/json/popular?callback=yourFunction'
    
    getData(url, {}, function(result) {
    console.log(result);
    data = result;
    });
    

    Now that you have got your data, you can easily add it in your html via templates or as raw text

    Raw text :

    $('#post-result').append(JSON.stringify(data));
    

    Oh and I highly recommend you put your application code just before the closing body tag.