7

I'm trying locally to get JSONP to give me a correct response and pass it into my callback function jsonp_callback. Using code from: How do I set up JSONP?

header('content-type: application/json; charset=utf-8');
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
echo $_GET['jsonpCallback'] . '('.json_encode($data).')';

and

$.ajax({
    url: 'jsonp-response.php', 
    dataType:'jsonp',
    jsonp: 'jsonp_callback',
    success: function (r){
        console.log(r);
    }
});


function jsonp_callback (r){
    console.log('jsonp_callback:',r);
}

Sofar I'm getting a Response which looks like:

jQuery1102035954900085926056_1381230228656({"a":1,"b":2,"c":3,"d":4,"e":5})

Looking at the first answer from Testing a static jsonp response I think I'm doing it correctly but I'm not sure why jQuery gives me a unique string.

How would I make my response look like this ?

jsonp_callback({"a":1,"b":2,"c":3,"d":4,"e":5})
Community
  • 1
  • 1
invad0r
  • 908
  • 1
  • 7
  • 20

2 Answers2

1

Here is the snippets from my code.. If it solves your problems..

Client Code :

Set jsonpCallBack : 'photos' and dataType:'jsonp'

 $('document').ready(function() {
            var pm_url = 'http://localhost:8080/diztal/rest/login/test_cor?sessionKey=4324234';
            $.ajax({
                crossDomain: true,
                url: pm_url,
                type: 'GET',
                dataType: 'jsonp',
                jsonpCallback: 'photos'
            });
        });
        function photos (data) {
            alert(data);
            $("#twitter_followers").html(data.responseCode);
        };

Server Side Code (Using Rest Easy)

@Path("/test_cor")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String testCOR(@QueryParam("sessionKey") String sessionKey, @Context HttpServletRequest httpRequest) {
    ResponseJSON<LoginResponse> resp = new ResponseJSON<LoginResponse>();
    resp.setResponseCode(sessionKey);
    resp.setResponseText("Wrong Passcode");
    resp.setResponseTypeClass("Login");
    Gson gson = new Gson();
    return "photos("+gson.toJson(resp)+")"; // CHECK_THIS_LINE
}
Community
  • 1
  • 1
Sanjay Kumar
  • 1,474
  • 14
  • 22
-1

Like this:

$.ajax({
    url: 'jsonp-response.php', 
    dataType:'jsonp',
    jsonp: 'jsonp_callback',
    success: jsonp_callback 
});

function jsonp_callback (r) {
    console.log('jsonp_callback:',r);
}

In your code you never actually used the jsonp_callback function that you defined. You simply wrote some anonymous success callback. jQuery noticed that you used an anonymous function and that's why it generated this random name so that it can invoke the anonymous callback.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Yes that passes into the function jsonp_callback. The response in the header still looks like `jQuery11020983548907097429_1381238805774({"a":1,"b":2,"c":3,"d":4,"e":5})` – invad0r Oct 08 '13 at 13:28