ajax POST跨域请求完美解决

来源:https://blog.csdn.net/danfeixia/article/details/71599304

方式:

js前端请求:

function getOcrInfo(imageData){
$.ajax({
   url: 'http://localhost:8080/LSWS/ws/ocr/getWebImageRecognitionJsonStringByBase64Image',
   type: 'post',
   dataType:'json',
   //async:false,
   data: {
        "imageData" : imageData
   },
   success:function(data){
      if(data.flag==0){
       var name=decodeURIComponent(data.name);
   var position=decodeURIComponent(data.position);

      }else{
      FR.Msg.alert("错误提示","获取识别结果失败,请重试!");
      
      
   },
   error:function(data){
       FR.Msg.alert("错误提示","获取识别结果失败,请重试!");
   }
});

服务器后端:

@RequestMapping(value="/getWebImageRecognitionJsonStringByBase64Image", method = RequestMethod.POST)
@ResponseBody
public String getWebImageRecognitionJsonStringByBase64Image(HttpServletRequest request,HttpServletResponse response,String imageData) {
String result = "";
//System.out.println(imageData);
try{
WebImageRecognition gr = new WebImageRecognition();
result = gr.getWebImageRecognitionJsonObjectByBase64Image(imageData);

response.addHeader("Access-Control-Allow-Origin", "*");   //用于ajax post跨域(*,最好指定确定的http等协议+ip+端口号)
response.setCharacterEncoding("utf-8");
//response.getWriter().write(result);
//response.getWriter().close();
}catch(Exception e){
e.printStackTrace();
logger.error("getGeneralRecognition:"+e);
result = "{\"flag\":\"1\",\"errorMessage\":\"server change error at OcrController!\"}";
}
   return result;
}

/*jQuery.support.cors = true;
$.ajax({
    async: true,
type: "post",
        url: "http://localhost:8686/user/login",
        data: param,
        dataType: "json",
        success: function(data){
    if(data['error']!='' && data['error']!=undefined){
    alert("用户名或密码错误!");
    }else{
    if(data['success']!='' && data['success']!=undefined){
    var userid = data['id'];
    var usertype = data['type'];
    var seurl='/logrobot/localLogin';
    var params={
    id:userid,
    ph:usern,
    ty:usertype,
    };
    var form = $('<form method="POST" action="' + seurl + '">');
            $.each(params, function(k, v) {
                form.append($('<input type="hidden" name="' + k +
                         '" value="' + v + '">'));
            });
            $('body').append(form);
            form.submit(); //自动提交
    }
    }
            return false;
        }
});

猜你喜欢

转载自blog.csdn.net/rentian1/article/details/80844906