加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax请求永远是304的解决方案

发布时间:2020-12-16 00:43:18 所属栏目:百科 来源:网络整理
导读:我之前写了一个NavigationService,用来做页面的Ajax导航,但是今天发现一个问题,在IE下面,发现Ajax的请求不会真正的被发送到服务器端,在IE里面,返回的永远是304。这个应该是IE的设计问题: 查了一下,发现这个博文里面提到了问题的本质: http://blog.s

我之前写了一个NavigationService,用来做页面的Ajax导航,但是今天发现一个问题,在IE下面,发现Ajax的请求不会真正的被发送到服务器端,在IE里面,返回的永远是304。这个应该是IE的设计问题:查了一下,发现这个博文里面提到了问题的本质:http://blog.sina.com.cn/s/blog_4b7809800100y1c3.html。“因为ajax请求的时候如果使用get方式请求,同时路径参数相同的时候,ajax会先从本地缓存中取,如果取到了它是不会去请求后台的”,知道了问题就好办了,照着文章中写的那样,给每个AJAX的请求都加一个请求参数,以保证URL永远不同。这个是修改之后的代码:

# require: jQuery
# Encapsulate the logic to dynamic load content by Url flag segment

class UrlFlagNaviListener
#public:
    constructor: (@m_container,@m_uiLoading,@m_uiError)->
        this.__addListener();

    naviContent: (contentAjaxUrl)->
        contentAjaxUrl = (contentAjaxUrl || window.location.hash).slice(1);
        this._naviContentImpl(contentAjaxUrl);

#protected:
    _naviContentImpl: (contentAjaxUrl) -> # to be overriden

#private:
        
    __addListener: ()->
        $(window).on("hashchange",()=>
            this.naviContent();
        );


class ContentNaviListener extends UrlFlagNaviListener
#protected:
    _naviContentImpl: (contentAjaxUrl) ->
        if (contentAjaxUrl isnt '')
            # cancel the previous page's deferred
            if (@m_prevRequest?.deferred.state() is 'pending')
                console.log("Previous request is cancelled.")
                @m_prevRequest.deferred.abort();
                @m_prevRequest.stopAnimation();

            @m_prevRequest = null;
            @m_container.hide();
            @m_uiError.hide();

            request = {};

            # Start animation and return the function to stop it
            request.stopAnimation = (()=>
                animation = ()=>@m_uiLoading.fadeIn(800).fadeOut(1000);
                animation();
                timer = setInterval(animation,2000);
                stopAnimation = ()=>
                    clearInterval(timer);
                    @m_uiLoading.stop().hide();
                return stopAnimation
            )();
            
            # Force IE9 refresh the ajax page
            leadingChar = if (contentAjaxUrl.indexOf("?") is -1) then "?" else "&"
            contentAjaxUrl += "#{leadingChar}timeStamp=#{new Date().getTime()}"

            request.deferred = $
                .get(contentAjaxUrl)
                .done( (data,textStatus,jqXHR)=>
                    request.stopAnimation();
                    @m_container.show().html(data) )
                .fail( ()=>
                    request.stopAnimation();
                    @m_uiError.show() )

            @m_prevRequest = request;

############
# Exports
############
window.ContentNaviListener = ContentNaviListener;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读