Ajax通过jsonp实现跨域访问,访问成功但走error不走success

刚开始json的格式:

{"dateli":[{"intro":"固定式","remarks":"割发代首","commId":"0006adc3-2b4e-4bbd-9e9e-45fa9b096a4d","price":"43.0","mdRelationId":"cd9e379c-9e98-49c0-b41e-93b932bf573a","commName":"后台"},{"intro":"固定式","remarks":"鬼地方","commId":"115460cb-9ae6-4057-bfcd-abc3b9426833","price":"2.0","mdRelationId":"cd9e379c-9e98-49c0-b41e-93b932bf573a","commName":"过任务"}]}


前台代码:

 $.ajax({
            url: "http://localhost/card/recharge",
            type: "get",
            dataType: "jsonp",
            jsonp:'callback',
            success: function (json) {
                    var jsonlist = json.dateli.length;
                    if (jsonlist > 0) {
                        var html = '';
                        for (var i = 0; i < jsonlist; i+=2) {
                           alert(json.dateli[i].price);  
                        }
                        $("#jiji").append(html);
                    }
            }
        });


后台代码:
@RequestMapping(value = "/card/recharge")
	public void cardRecharge(HttpServletRequest request,
			HttpServletResponse response, String str) {
		try {
			this.logger.info("进入首页,查询参数str=" + str);
			JSONObject json = JSONObject.fromObject(str);
			JSONArray jsonListTmp = new JSONArray();
			JSONObject tempJson = new JSONObject();
			CommDomain commDomain = new CommDomain();
			List<CommDomain> commList = this.serviceFactory.getCommServices().getCommDomain(commDomain);
			for(CommDomain commDomainTemp : commList){
				tempJson.put("intro", commDomainTemp.getIntro());
				tempJson.put("remarks", commDomainTemp.getRemarks());
				/*tempJson.put("createTime", String.valueOf(commDomainTemp.getCreateTime()));*/
				tempJson.put("commId", commDomainTemp.getCommId());
				tempJson.put("price", String.valueOf(commDomainTemp.getPrice()));
				tempJson.put("mdRelationId", commDomainTemp.getMdRelationId());
				tempJson.put("commName", commDomainTemp.getCommName());
				jsonListTmp.add(tempJson);
			}
			JSONObject aapJson = new JSONObject();
			aapJson.put("dateli", jsonListTmp);
			this.logger.info("返回结果=" + aapJson .toString());
			InputStream is = new ByteArrayInputStream(aapJson.toString().getBytes("UTF-8"));
			// copy it to response's OutputStream
			IOUtils.copy(is, response.getOutputStream());
			response.flushBuffer();
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return;
	}


原因: 用jsonp跨域访问, 会注册callback, 生产一个随机的callback,正确的jsonp格式应该是 callback({"id" : "1","name" : "小王"}); 

       所以我们需要定义callback,前台指定回调函数jsonpCallback:successCallback,后台指定返回的json格式:String jj = "successCallback("+aapJson+")";



修改后的前台代码:

  $.ajax({
            url: "http://localhost/card/recharge",
            type: "get",
            dataType: "jsonp",
            jsonp:'callback',
            jsonpCallback:"successCallback",
            success: function (json) {
                    var jsonlist = json.dateli.length;
                    if (jsonlist > 0) {
                        var html = '';
                        for (var i = 0; i < jsonlist; i+=2) {
 			alert(json.dateli[i].price);      
                        }
                        $("#jiji").append(html);
                    }

            }
        });

修改后的后台代码:
@RequestMapping(value = "/card/recharge")
	public void cardRecharge(HttpServletRequest request,
			HttpServletResponse response, String str) {
		try {
			this.logger.info("进入首页,查询参数str=" + str);
			JSONObject json = JSONObject.fromObject(str);
			JSONArray jsonListTmp = new JSONArray();
			JSONObject tempJson = new JSONObject();
			CommDomain commDomain = new CommDomain();
			List<CommDomain> commList = this.serviceFactory.getCommServices().getCommDomain(commDomain);
			for(CommDomain commDomainTemp : commList){
				tempJson.put("intro", commDomainTemp.getIntro());
				tempJson.put("remarks", commDomainTemp.getRemarks());
				tempJson.put("commId", commDomainTemp.getCommId());
				tempJson.put("price", String.valueOf(commDomainTemp.getPrice()));
				tempJson.put("mdRelationId", commDomainTemp.getMdRelationId());
				tempJson.put("commName", commDomainTemp.getCommName());
				jsonListTmp.add(tempJson);
			}
			JSONObject aapJson = new JSONObject();
			aapJson.put("dateli", jsonListTmp);
			String jj = "successCallback("+aapJson+")";
			this.logger.info("返回结果=" + jj.toString());
			InputStream is = new ByteArrayInputStream(
					jj.toString().getBytes("UTF-8"));
			// copy it to response's OutputStream
			IOUtils.copy(is, response.getOutputStream());
			response.flushBuffer();
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return;
	}



总结:用jsonp跨域访问, 一定需要注意callback,或者直接定义一个callback,例如这样:jsonpCallback:"successCallback",

           后台也需要注意, 返回的json值得格式,因为用jsonp,所以需要用这样的格式:successCallback({"id" : "1","name" : "小王"});







没有更多推荐了,返回首页