2

I found this question on setting the response type to json from a jsp but I'm in need of setting the response type to jsonp for cross-domain access. Would it still be this:

response.setContentType("application/javascript");

and just wrapping the response from the jsp in callbackfunction( + content + ) or is there something more that needs to be done?

Community
  • 1
  • 1
Charlie G
  • 814
  • 9
  • 22
  • possible duplicate of [Best content type to serve JSONP?](http://stackoverflow.com/questions/111302/best-content-type-to-serve-jsonp) – loganfsmyth Dec 21 '12 at 16:16
  • I saw that answer, but I was more specifically asking if there's anything else I need to do to access it correctly on the other end. – Charlie G Dec 21 '12 at 18:04

3 Answers3

3

I recently had to do this. In the server side I had something like so:

string callbackName = queryMap['callback']; //jquery will pass in some name in our .getJSON call below
string jsonData = getJsonData();
string jsonp = callbackName + "(" + jsonData + ")";

response.SetContentType('application/javascript');
response.Send( jsonp );

And in the javascript it was something like so:

var url = getUrl() + "?callback=?";
$.getJSON(url,function(onSuccessData){ alert(onSuccessData); });
dchhetri
  • 6,926
  • 4
  • 43
  • 56
0

To support cross-domain access in javascript you can use $.support.cors = true;
Other than that you can set content-type to application/javascript for jsonp.

bwhite
  • 2,643
  • 1
  • 18
  • 8
  • I found the application/javascript answer after posting this, thanks. My question was really geared toward how create the JSP so that it returns the correct jsonp data. Should it be formated by callbackfunction + '(' + content + ')' or what? – Charlie G Dec 21 '12 at 18:06
0

jsp:

 String str = "{\"appNo\":\"" + "2" + .....+ "\"}";
    String json = "m1(" + str + ")";
    response.getWriter().write(json);

html:

 $.ajax({
          type: 'GET',    
          url: url,
          dataType: "jsonp",
          crossDomain: true,          
          cache:false,
           jsonp:"callback",
          success: function(data){  }....
   });

This is the code for my jsp

  • "This is the code for my jsp, do the result same as yours?" - You shouldn't have to ask a question to have a good answer. I recommend you be sure this is the right answer and have the confidence to say so. – Russia Must Remove Putin Sep 02 '14 at 02:41