ajax 请求 JAVA WEB应用程序实现跨域请求

来源:互联网 发布:c语言命名规则 编辑:程序博客网 时间:2024/06/08 19:38

HTML5页面


<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery实现JSONP</title>
</head>
<body>
    <div id="mydiv">
        <button id="btn">点击</button>
    </div>
    
    <div id="showcontent">
   
    </div>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("#btn").click(function(){


/*
            $.ajax({
                async : true,
                url : "http://localhost:8080/app/chenxinxue",
                type : "GET",
                dataType : "jsonp", // 返回的数据类型,设置为JSONP方式
                jsonp : 'callback', //指定一个查询参数名称来覆盖默认的 jsonp 回调参数名 callback
                jsonpCallback: 'handleResponse', //设置回调函数名
                data : {
                    q : "javascript", 
                    count : 1
                }, 
                success: function(date){
                    alert(date);
                }
            });
            
            */
           
           
               $.ajax({  
       type : "get",  
       async:false,  
       url : "http://localhost:8080/app/chenxinxue?sid=1494&busiId=101",  
       dataType : "jsonp",//数据类型为jsonp  
       jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数  
       success : function(data){  
           $("#showcontent").text("Result:"+data.result)  
       },  
       error:function(){  
           alert('fail');  
       }  
   });   
}); 


    });
</script>

</html>






JAVA WEB 后台程序。


package com.example;


import java.util.HashMap;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController  
@EnableAutoConfiguration  
public class Example
{  
      
    @RequestMapping("/")  
    String home() {  
        return "Hello World!";  
    }  
      
    @RequestMapping("/hello/{myName}")  
    String index(@PathVariable String myName) 
    {  
        return "Hello "+myName+"!!!";  
    }
    
    @RequestMapping("/app/{myName}")
    Object cxx(HttpServletRequest request,HttpServletResponse response)
    {
    StringBuffer sbf = new StringBuffer();
     
    try {  
    response.setContentType("text/html;charset=utf-8");
             response.setContentType("text/plain");  
             response.setHeader("Pragma", "No-cache");  
             response.setHeader("Cache-Control", "no-cache");  
             response.setDateHeader("Expires", 0);  
             
             Map<String,String> map1 = new HashMap<String,String>();   
             map1.put("userName", "陈新学");
             map1.put("age", "18");  
             map1.put("addsress", "学府路软件产业基地");  
             
             JSONArray array = JSONArray.fromObject(map1);
             
             String jsonstr = array.toString();
             
             Map<String,String> map = new HashMap<String,String>();   
             map.put("result", jsonstr);  
             
             JSONObject resultJSON = JSONObject.fromObject(map); //根据需要拼装json  
           
             String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数  
             
             sbf.append(jsonpCallback);
             
             sbf.append("("+resultJSON.toString(1,1)+")");///返回jsonp格式数据  
           } catch (Exception e)
      {  
          
           }  
     
    return sbf.toString();
    }
    
}

原创粉丝点击