Search code examples
jsonrestjqueryjsonp

how to set jsonp callback in retrieving restful web service data via jquery


I have asked a question regarding invalid label on firebug which happens when I try to retrieve data from my restful web service. Most of the answers I received was about setting a callback function. but I can't seem to get the right juice from it. can you show me an exact code on how to do it? or atleast correct the code here:

        type: "GET",
        cache: false, 
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        processdata:true,
        jsonp: false, jsonpCallback: "success",
        url: 'http://localhost:8732/Service1/data/10',

        success : function success(data) {
            jsonResponse = eval("(" + data + ")");
            alert(jsonResponse)
        },
        error : function(req,status, ex) {

            alert(ex);
        }

Thanks,


Solution

  • Wow, you've got a lot of unnecessary stuff there. Try this:

    $.ajax({
        url: 'http://localhost:8732/Service1/data/10',
        dataType: 'jsonp',
        error: function(req, status, ex) {
            // your code here
        },
        success: function(data) {
            //your code here
            // Please note: you don't need to 'eval' the json response.
            // The 'data' variable will be loaded with the object that the json string represents.
            // By the way, don't use 'eval', ever.
        }
    });
    

    jQuery will take care of the callback on the url. See here: http://api.jquery.com/jQuery.ajax/

    UPDATE Why jsonp? If you're getting this from localhost, why not just json? As discussed in the comments below, your server currently is not capable of a jsonp response, but it can do json.