JSONP处理跨域请求 --org.json

1, Ajax请求

(同一ip, 当前应用为8086端口, 要访问的后端接口为8088端口, 出现跨域请求问题)

 $.ajax({
              url: 'http://10.171.1.34:8088/ssm_test/login.do',
              type: 'GET',
              dataType: 'JSONP',
              jsonp:"callback",  //Jquery生成验证参数的名称
              data: {
                  name: _this.username,
                  pwd: _this.password
              },
              success: function (res) {
                console.log("登陆成功");
              },
              error: function (err) {
                console.log("返回出错了");
              }
        });

2, 对应后端接口处理

将返回数据封装成callback函数格式, 结果数据result 需求进行JSON格式处理, 这里需要用到org.json的jar包

//登陆
	@RequestMapping("/login.do")
	@ResponseBody
	public Object guess(String name, String pwd, @RequestParam("callback") String callback){
		boolean b = 
				vueLoginService.login(name, pwd);
		System.out.println("b: " + b);
		JSONObject result = new JSONObject();
		if(b){
			result.put("state", "200");
	        result.put("data", "登陆成功");
	        return callback+"(" + result.toString() + ")";
		} else {
			result.put("state", "999");
	        result.put("data", "登陆失败");
	        return callback+"(" + result.toString() + ")";
		}
	}

json-20180813.jar: 

链接:https://pan.baidu.com/s/1YmMnUkCdMDFx9npbwIdNrA 
提取码:ukoo 

猜你喜欢

转载自blog.csdn.net/weixin_39039342/article/details/85258228