ajax前台获取后台数据的问题

 

初级java程序员,天天写js

遇到一些问题,本人比较笨,总结一下

我前台需要获取后台的三个信息 

{"company":true,"city":true,"expert":true}
$.ajax({
        url: prefix+'/isInTime',
        type: 'GET' ,
        dataType: "json",
        data:  '' ,
        async: true,
        contentType: "application/json",
        success: function (resp) {
            alert(resp.company)
        },
        error: function () {
            alert("时间控制请求失败请联系管理员!")
        }
    });

我是get请求,

这其中呢dataType设置的是后台返回前台的数据类型,这里设置为json数据,

而这个contentType是设置我们前台发送到后台的数据类型,

这是我之前的写的

@ResponseBody
	@GetMapping("/isInTime")
	@RequiresPermissions("jszxpjb:pjb:pjb")
	public Map<String, Boolean>  isComInTime(){
		Map<String, Boolean> map = timeControlService.isinTime();
		String str = JSONObject.toJSONString(map);
		return str ;
	}

将map转换成str,就和json差不多格式那种,但是运行后哈,那个ajax他就不走success function了。。。。

我就到处百度一下,这里有几种写法,

1.后台就像这样,返回json格式的string字符串,

@ResponseBody
	@GetMapping("/isInTime")
	@RequiresPermissions("jszxpjb:pjb:pjb")
	public Map<String, Boolean>  isComInTime(){
		Map<String, Boolean> map = timeControlService.isinTime();
		String str = JSONObject.toJSONString(map);
		return str ;
	}

那么前台

$.ajax({
        url: prefix+'/isInTime',
        type: 'GET' ,
        dataType: "text",
        data:  '' ,
        async: true,
        contentType: "application/json",
        success: function (resp) {
             var obj=JSON.parse(resp)
            alert(obj.company)
        },
        error: function () {
            alert("时间控制请求失败请联系管理员!")
        }
    });

得到的是string类型,var obj=JSON.parse(resp) 将string转换成json对象,这样就可以获取属性了

想获取属性就写   resp.company     就可以了

2.

前台是这样

$.ajax({
        url: prefix+'/isInTime',
        type: 'GET' ,
        dataType: "json",
        data:  '' ,
        async: true,
        contentType: "application/json",
        success: function (resp) {
            alert(resp.company)
        },
        error: function () {
            alert("时间控制请求失败请联系管理员!")
        }
    });

接收数据为json

后台这样

	@ResponseBody
	@GetMapping("/isInTime")
	@RequiresPermissions("jszxpjb:pjb:pjb")
	public Map<String, Boolean>  isComInTime(){
		Map<String, Boolean> map = timeControlService.isinTime();
		return map;
	}

直接就可以取属性了

其实第二种少了两行代码

希望对您有帮助

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值