Post data to JsonP

后端 未结 7 1329
傲寒
傲寒 2020-11-22 07:22

Is it possible to post data to JsonP? Or does all data have to be passed in the querystring as a GET request?

I have alot of data that I need to send to the service,

7条回答
  •  情话喂你
    2020-11-22 08:13

    There's a (hack) solution I've did it many times, you'll be able to Post with JsonP. (You'll be able to Post Form, bigger than 2000 char than you can use by GET)

    Client application Javascript

    $.ajax({
      type: "POST", // you request will be a post request
      data: postData, // javascript object with all my params
      url: COMAPIURL, // my backoffice comunication api url
      dataType: "jsonp", // datatype can be json or jsonp
      success: function(result){
        console.dir(result);
      }
    });
    

    JAVA:

    response.addHeader( "Access-Control-Allow-Origin", "*" ); // open your api to any client 
    response.addHeader( "Access-Control-Allow-Methods", "POST" ); // a allow post
    response.addHeader( "Access-Control-Max-Age", "1000" ); // time from request to response before timeout
    

    PHP:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Max-Age: 1000');
    

    Doing like this, you are opening your server to any post request, you should re-secure this by providing ident or something else.

    With this method, you could also change the request type from jsonp to json, both work, just set the right response content type

    jsonp

    response.setContentType( "text/javascript; charset=utf-8" );
    

    json

    response.setContentType( "application/json; charset=utf-8" );
    

    Please not that you're server will no more respect the SOP (same origin policy), but who cares ?

提交回复
热议问题