我在本地尝试让JSONP给我一个正确的响应,并将其传递到我的回调函数jsonp_callback中。使用来自: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).')';和
$.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);
}到目前为止,我得到的响应看起来是这样的:
jQuery1102035954900085926056_1381230228656({"a":1,"b":2,"c":3,"d":4,"e":5})看一下来自Testing a static jsonp response的第一个答案,我认为我做得很正确,但是我不确定为什么jQuery会给我一个唯一的字符串。
我该如何使我的响应看起来像这样呢?
jsonp_callback({"a":1,"b":2,"c":3,"d":4,"e":5})发布于 2014-03-31 11:09:49
下面是我的代码片段。如果它解决了你的问题..
客户端代码:
设置jsonpCallBack:‘照片’,数据类型:‘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);
};服务器端代码(使用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
}发布于 2013-10-08 21:16:56
如下所示:
$.ajax({
url: 'jsonp-response.php',
dataType:'jsonp',
jsonp: 'jsonp_callback',
success: jsonp_callback
});
function jsonp_callback (r) {
console.log('jsonp_callback:',r);
}在您的代码中,您从未实际使用过您定义的jsonp_callback函数。你只是写了一些匿名的成功回调。jQuery注意到您使用了一个匿名函数,这就是为什么它会生成这个随机名称,以便它可以调用匿名回调。
https://stackoverflow.com/questions/19247448
复制相似问题