使用jsonp方式完成跨域资源的访问(struts2)

使用struts2完成jsonp的访问,本示例是关于获取时间的

效果:

这里写图片描述

action

package actions;

import java.text.DateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;



public class TimeAction extends ActionSupport {


    private String time;
    private String callback;

    public TimeAction(){
        time = "{\"time\":\"" + DateFormat.getDateTimeInstance().format(new Date()) + "\"}";  /*初始化时间*/

    }

    @Override
    public String execute() throws Exception {
        if(callback != null){
            time = callback + "(" + time + ")";
        }

        return "time";
    }

    public String getTime() {
        return time;
    }

    public String getCallback() {
        return callback;
    }

    public void setCallback(String callback) {
        this.callback = callback;
    }

    public void setTime(String time) {
        this.time = time;
    }




}

struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">


<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.i18n.encoding" value="utf-8"></constant>

    <package name="index" namespace="/" extends="struts-default">
        <action name="getTime" class="actions.TimeAction">
            <result name="time">/WEB-INF/time.jsp</result>
        </action>
    </package>


</struts>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

    <filter>
        <filter-name>Struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

time.jsp

${requestScope.time}

发布后 通过demo页面访问测试

demo.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>ajax使用jsonp方式跨域</title>
    <p>显示十条时间记录</p>
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>

<body>


<script>
    /*使用jsonp方式完成跨域资源的访问*/

   var x = setInterval("getData()", 1000);
   var i = 0;

   //回调函数在获取数据成功后执行
   function showTime(data) {
     var p = document.createElement("p");
     p.innerHTML = "<span style='color:red'>" + ++i + ":<\/span> " + data.time;
     document.body.appendChild(p);
   }

   function getData(){
       $.ajax({
           url: "http://localhost:8080//testJsonp/getTime", //url
           type: "get",
           dataType: 'jsonp',
           jsonp: 'callback',  //jsonp请求中指定回调函数的参数名称为callback,即action?callback=xx
           jsonpCallback: 'showTime',   //指定jsonp请求对应的回调函数名称为showTime即callback=showTime
           success:function(data) {
           /*
               var p = document.createElement("p");
               p.innerHTML = "<span style='color:red'>" + ++i + ":<\/span> " + data.time;
               document.body.appendChild(p);*/
           },
           complete: function (XMLHttpRequest, textStatus) {
               //console.info("textStatus : " + textStatus);

               var len = i;
               if(len == 10) {
                   clearInterval(x);
                   return;
               }
                /*
               for(var tval in this) {
                 console.log(tval + " : "+ this[tval] + "\n"); // this是指调用本次AJAX请求时传递的options参数
               }
               */
           }

       });


   }


</script>


</body>
</html>

github: https://github.com/joker-pper/jsonp-study.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值