前端接收 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 必须是使用默认的异步方式了

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

function getSearchResult(query) {
		 $.ajax({
	        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>",//这个名字可以改,但是要与服务端设置的对应
	       <span style="color:#ff0000;"> dataType: 'jsonp',</span>
	        data: {format:"jsonp",name:"aaa"},//async: false,//false 为同步方式
	        success: function (data) {
	        	alert(data.length)
	        	/* for(var i = 0;i < data.length;i++) {
	        		for(var j in data[i]) {
	        			alert(j+" : "+data[i][j])
	        		}
	        	} */
			}
		});  
		/* $.get(  //这个默认异步,故result 无法被赋值
			"http://10.2.6.81:2360/leisurehotel/search?return=hotelid,hotelname§ion=1,3",function(data){
				result1 = 'aaa '+ data 
			}//返回的data是字符串类型
		); */ 
		return result;
	}


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

package com.ctrip.search.engine;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.QueryStringDecoder;

public class NettyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
	
	StringBuilder sb = new StringBuilder();
	JSONArray jsonarray = new JSONArray();
	JSONObject jsonobject = new JSONObject();
	JSONPObject jsonpobject = new JSONPObject();
	
	public NettyServerHandler() {
		jsonarray.add(getJsonObj("name","ar.arch.lolplay"));
		jsonarray.add(getJsonObj("name","ar.arch.tict"));
		jsonarray.add(getJsonObj("name","ar.arch.gfl"));
		jsonarray.add(getJsonObj("name","ar.arch.leurehotel"));
		<span style="color:#ff0000;">jsonpobject.setFunction("myjsonpcallbacknameinalllowercase");
		jsonpobject.addParameter(jsonarray);</span>
		
	}
	
	public JSONObject getJsonObj(String name,String value) {
		JSONObject jsonobj = new JSONObject();
		jsonobj.put(name,value);
		return jsonobj;
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
		cause.printStackTrace();
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx,FullHttpRequest msg) //
			throws Exception {//函数执行次数?
		//解析get请求参数
		QueryStringDecoder decoder = new QueryStringDecoder(msg.getUri());  
		Map<String,List<String>> parame = decoder.parameters();  
		for(Entry<String,List<String>> entry : parame.entrySet()) {
			System.out.println(entry.getKey() + " : " +entry.getValue());
		}
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,OK); // 响应
		response.headers().set(CONTENT_TYPE,"text/html; charset=UTF-8");
		ByteBuf responseContentByteBuf = Unpooled.copiedBuffer(<span style="color:#ff0000;">jsonpobject.toString()</span>.getBytes(Charset.forName("utf-8")));
		response.headers().set("Access-Control-Allow-Origin","*"); // 跨域
		response.headers().set(CONTENT_LENGTH,responseContentByteBuf.readableBytes());
		response.content().writeBytes(responseContentByteBuf);
		responseContentByteBuf.release();//zuoyong?
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);//zuoyong?
	}
	
}
原文链接:https://www.f2er.com/json/289419.html

猜你在找的Json相关文章