前端接收 get 请求,用jsonp 解决跨域问题, 需要服务端的response 也要jsonp 类型

前端之家收集整理的这篇文章主要介绍了前端接收 get 请求,用jsonp 解决跨域问题, 需要服务端的response 也要jsonp 类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. 解决跨域必须在ajax 方法中dataType 设置为jsonp

2. 此时服务端返回的就必须是jsonp 类型的,而不是json 类型的

3. 客户端js 代码中ajax 方法还要设置jsonpCallback 这个属性

4. jquery 版本据说用1.5以上,我用jquery-1.7.2.min.js

5.这个难说是BUG 还是特定写法,总之解决

6.设置了jsonp 返回之后,async:false 这个选项就不能用了,即不能用同步,ajax 必须是使用默认的异步方式了

前端代码(红色是此场景的必须的写法)

  1. function getSearchResult(query) {
  2. $.ajax({
  3. type: "get",url: "http://10.32.17.7:2360?<span style="color:#ff0000;">prefix=?</span>",<span style="color:#ff0000;">jsonpCallback</span>:"<span style="color:#ff0000;">myjsonpcallbacknameinalllowercase</span>",//这个名字可以改,但是要与服务端设置的对应
  4. <span style="color:#ff0000;"> dataType: 'jsonp',</span>
  5. data: {format:"jsonp",name:"aaa"},//async: false,//false 为同步方式
  6. success: function (data) {
  7. alert(data.length)
  8. /* for(var i = 0;i < data.length;i++) {
  9. for(var j in data[i]) {
  10. alert(j+" : "+data[i][j])
  11. }
  12. } */
  13. }
  14. });
  15. /* $.get( //这个默认异步,故result 无法被赋值
  16. "http://10.2.6.81:2360/leisurehotel/search?return=hotelid,hotelname§ion=1,3",function(data){
  17. result1 = 'aaa '+ data
  18. }//返回的data是字符串类型
  19. ); */
  20. return result;
  21. }


后端代码(红色是此场景的必须的写法)

  1. package com.ctrip.search.engine;
  2.  
  3. import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
  4. import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
  5. import static io.netty.handler.codec.http.HttpResponseStatus.OK;
  6. import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
  7.  
  8. import java.nio.charset.Charset;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.Map.Entry;
  12.  
  13. import com.alibaba.fastjson.JSON;
  14. import com.alibaba.fastjson.JSONArray;
  15. import com.alibaba.fastjson.JSONObject;
  16. import com.alibaba.fastjson.JSONPObject;
  17. import com.alibaba.fastjson.serializer.SerializerFeature;
  18.  
  19. import io.netty.buffer.ByteBuf;
  20. import io.netty.buffer.Unpooled;
  21. import io.netty.channel.ChannelFutureListener;
  22. import io.netty.channel.ChannelHandlerContext;
  23. import io.netty.channel.SimpleChannelInboundHandler;
  24. import io.netty.handler.codec.http.DefaultFullHttpResponse;
  25. import io.netty.handler.codec.http.FullHttpRequest;
  26. import io.netty.handler.codec.http.FullHttpResponse;
  27. import io.netty.handler.codec.http.QueryStringDecoder;
  28.  
  29. public class NettyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
  30. StringBuilder sb = new StringBuilder();
  31. JSONArray jsonarray = new JSONArray();
  32. JSONObject jsonobject = new JSONObject();
  33. JSONPObject jsonpobject = new JSONPObject();
  34. public NettyServerHandler() {
  35. jsonarray.add(getJsonObj("name","ar.arch.lolplay"));
  36. jsonarray.add(getJsonObj("name","ar.arch.tict"));
  37. jsonarray.add(getJsonObj("name","ar.arch.gfl"));
  38. jsonarray.add(getJsonObj("name","ar.arch.leurehotel"));
  39. <span style="color:#ff0000;">jsonpobject.setFunction("myjsonpcallbacknameinalllowercase");
  40. jsonpobject.addParameter(jsonarray);</span>
  41. }
  42. public JSONObject getJsonObj(String name,String value) {
  43. JSONObject jsonobj = new JSONObject();
  44. jsonobj.put(name,value);
  45. return jsonobj;
  46. }
  47. @Override
  48. public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
  49. cause.printStackTrace();
  50. }
  51. @Override
  52. protected void channelRead0(ChannelHandlerContext ctx,FullHttpRequest msg) //
  53. throws Exception {//函数执行次数
  54. //解析get请求参数
  55. QueryStringDecoder decoder = new QueryStringDecoder(msg.getUri());
  56. Map<String,List<String>> parame = decoder.parameters();
  57. for(Entry<String,List<String>> entry : parame.entrySet()) {
  58. System.out.println(entry.getKey() + " : " +entry.getValue());
  59. }
  60. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,OK); // 响应
  61. response.headers().set(CONTENT_TYPE,"text/html; charset=UTF-8");
  62. ByteBuf responseContentByteBuf = Unpooled.copiedBuffer(<span style="color:#ff0000;">jsonpobject.toString()</span>.getBytes(Charset.forName("utf-8")));
  63. response.headers().set("Access-Control-Allow-Origin","*"); // 跨域
  64. response.headers().set(CONTENT_LENGTH,responseContentByteBuf.readableBytes());
  65. response.content().writeBytes(responseContentByteBuf);
  66. responseContentByteBuf.release();//zuoyong?
  67. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);//zuoyong?
  68. }
  69. }

猜你在找的Json相关文章