Returning JSONP instead of JSON from a JSP

前端 未结 3 795
梦毁少年i
梦毁少年i 2021-01-22 20:06

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:

相关标签:
3条回答
  • 2021-01-22 20:48

    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); });
    
    0 讨论(0)
  • 2021-01-22 20:53

    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

    0 讨论(0)
  • 2021-01-22 21:04

    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.

    0 讨论(0)
提交回复
热议问题