correct JSONP Response

不羁岁月 提交于 2019-12-23 09:12:09

问题


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})

回答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
}



回答2:


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.



来源:https://stackoverflow.com/questions/19247448/correct-jsonp-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!