昨天帮同事从其余服务器传过来的json数据进行处理,遇到该问题。开始个人思路是用ajax直接请求把数据弄出来就OK了,然而出错了.缘由是我使用的ajax 返回类型为json,默认ajax阻止跨服获取数据的。结合其余博文,ajax的dataType使用jsonp来解决此问题。开始以为jsonp与json的使用相似,一步步的写着代码,以下: html
$.ajax({ type:'get', async:false, url:'http://112.11.131.238/nanhunongjing/GetCollectInforByCollectId?serverTime=384', dataType:'jsonp', cache:true, contentType:'application/x-www-form-urlencoded;charset=utf-8', jsonp: "callback",//传递给请求处理程序或页面的,用以得到jsonp回调函数名的参数名(默认为:callback) jsonpCallback:"callBackFun",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名 success:function(data){ // var json = $.parseJSON(data); alert(data[0].xxx); }, error:function(XMLHttpRequest, textStatus, errorThrown){ alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(XMLHttpRequest.responseText); alert(textStatus); alert(errorThrown); console.log(textStatus); } });
看着没问题,其实问题让人难一理解。执行上述代码始终执行error内的方法,用火狐查看调试,也看不出什么端倪。 java
页面alert输出 ajax
status 200
readyState 4
responseText null
errorThrown Error: callBackFun was not called
textStatus parsererror
咱们看到这些信息,通常就上网上查。。。。。 json
jsonpCallback 默认不写会生成一个名字,如jQuery172031072511965160154_140679384671 跨域
这是回调函数的名字。 服务器
我出错的重点也在这里,不明白回调是什么意思,怎么个回调法???? app
借鉴http://www.cnblogs.com/know/archive/2011/10/09/2204005.html该博主的写法。发现jsonp处理返回是以 async
回调函数名("json")总体返回的(例callBackFun(“{'x':'x'}”))。再请求时向后台传入了参数callback,也即回调函数名。 函数
后台处理程序: 测试
String callBackFun = hsRequest.getParameter("callback"); System.out.println("///"+callBackFun); hsResponse.getWriter().print(callBackFun+"([{\"xxx\":1,\"hs\":\"测试\"}])");相似以上代码处理。
要得到json数据,必定要注意返回数据的格式。
经过上述构思,不可能让咱们跨域去写一个回调函数,这种显然不可以适合应用环境。
我就换了另外一种获取数据的办法,利用httpClient去模拟请求获取远程服务端的数据,代码以下:
HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://112.11.131.238/nanhunongjing/GetCollectInforByCollectId?serverTime=384"); try { HttpResponse httpResponse = client.execute(httpGet); //响应状态 System.out.println("响应状态:"+httpResponse.getStatusLine()); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { /* 转化为文本信息 * 并转码 * */ result = EntityUtils.toString(entity,"utf-8"); System.out.println(result); result = new String(result.getBytes("utf-8"),"iso8859-1"); //hsResponse.getWriter().print(result); String callBackFun = hsRequest.getParameter("callback"); System.out.println("///"+callBackFun); hsResponse.getWriter().print(callBackFun+"([{\"xxx\":1,\"hs\":\"测试\"}])"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ //关闭链接释放资源 client.getConnectionManager().shutdown(); }在httpGet()写入本身的url
获取的数据通常已是json数据了。若是不是,我猜你也知道怎么去写,我这就很少说了。其余详细介绍本身在网上搜吧!多看看总会有解决办法,不要坐等别人给你说给你写。
有些不足的地方请包涵,谢谢。但愿对有问题的朋友有帮助!!!