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})
JSON with Padding — JSONP for short — is a technique that allows developers to bypass the same-origin policy enforced by browsers by using the <script> element's nature. The policy disallows reading any responses sent by websites whose origins are different from the one currently used.
JSONP has some other limitations, too: It can only be used for GET requests, and there's no general way to prevent cross-site request forgeries*. It's bad for private data, since any site on the web could hijack a JSONP response if the URL is known.
Standard JSON Asynchronous requestThe browser makes an asynchronous POST request to the server slapping its parameters to the service in the body. The server responds with a string of JSON data. A success handler of the request fires and the string is converted into a Javascript Object to be used in the application.
Method to use JSONP: In HTML code, include the script tag. The source of this script tag will be the URL from where the data to be retrieve. The web services allow to specify a callback function. In the URL include the callback parameter in the end.
Here is the snippets from my code.. If it solves your problems..
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);
};
@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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With