草庐IT

javascript - AJAX POST 请求被缓存

coder 2024-05-03 原文

在我的 Web 应用程序中,我向 url /navigate.php 发送了一个 POST 请求。它按应有的方式工作。

问题是,这个 Web 应用程序应该也可以离线工作。我将在由于连接问题无法完成请求时显示通知,当问题解决后用户可以再次同步。

当我出于调试目的断开互联网连接时,我发现每次请求仍然返回 200 状态代码。

我错了,POST 请求不应该被浏览器缓存吗?

在 Stack Overflow 上搜索后,我尝试了这里写的解决方案。

我在 url 中附加了一个缓存 bust (new Date().getTime()),但没有任何变化。请求仍然以 200 返回。

我尝试从服务器 (PHP/Ubuntu) 发送以下 header :

header("Expires: Sat, 01 Jan 2005 00:00:00 GMT");
header("Last-Modified: ".gmdate( "D, d M Y H:i:s")."GMT");
header("Cache-Control: no-cache, no-store");
header("Pragma: no-cache");

我没有将 jQuery 用于 AJAX(因为我只需要将它用于 AJAX,没有别的),否则我会使用它的 cache 选项,并将其设置为 。但我猜它做的是同样的事情,将缓存中断附加到 url。

我正在使用以下代码发送请求:

define([],function(){

var a=[

    function(){return new XMLHttpRequest()},
    function(){return new ActiveXObject("Msxml2.XMLHTTP")},
    function(){return new ActiveXObject("Msxml3.XMLHTTP")},
    function(){return new ActiveXObject("Microsoft.XMLHTTP")}

];

    var o=function(){

        var r=false;

        for(var i=0;i<a.length;i++) {

            try{

                r=a[i]();

            } catch(e) {

                continue;

            }

            break;

        }

        return r;

    };

    var verifyParam = function(param) {
        if(typeof param === "undefined" || param === null) {
            return false;
        } else {
            return true;
        }
    };

    var checkParam = function(param,defaultValue) {
        if(!verifyParam(param)) {
            return defaultValue;
        } else {
            return param;
        }
    };

    var generateCacheBust = function() {
        return (new Date().getTime());
    };

    var request = function(url,method,dataInPost,initCallback,callback,error) {

        var req = o();

        if(!req) return false;

        initCallback = checkParam(initCallback,function(){});

        callback = checkParam(callback,function(){});

        error = checkParam(error,function(){});

        initCallback(req);

        req.open(method,url,true);

        if(dataInPost) {

            req.setRequestHeader('Content-type','application/x-www-form-urlencoded');

        }

        req.onreadystatechange = function() {

            if(req.readyState!=4) {

                return;

            }

            try {

                if(req.status!=200 && req.status!=304) {

                    error(req.status);

                    return;

                } else {

                    callback(req);

                }

            } catch (e) {

                error(req.status);

                return;

            }

        }

        if(req.readyState == 4) return;

        try {

            req.send(dataInPost);

        } catch (e) {

            error(req.status);

            return;

        }

    };

    var dataToString = function(data) {

        var string = '';

        for(var key in data) {

            string += (encodeURIComponent(key)+'='+encodeURIComponent(data[key])+'&');

        }

        return string.substring(0,string.length-1);

    }

    var formattedResponse = function(req,type) {

        var responseData = req.responseText;

        if(type=="json") {

            return JSON.parse(responseData);

        } else {

            return responseData;

        }

    }

    var get = function(params) {

        if(!verifyParam(params.url)) { return false; }

        params.data = checkParam(params.data,{});

        params.responseType = checkParam(params.responseType,'text');

        params.init = checkParam(params.init,function(){});

        params.success = checkParam(params.success,function(){});

        params.error = checkParam(params.error,function(){});

        params.cache = checkParam(params.cache,true);

        if(!params.cache) {params.data.cacheBust = generateCacheBust();}

        request(params.url+'?'+dataToString(params.data),"GET",false,params.init,function(req){

            params.success(formattedResponse(req,params.responseType));

        },params.error);

    };

    var post = function(params) {

        if(!verifyParam(params.url)) { return false; }

        params.data = checkParam(params.data,{});

        params.responseType = checkParam(params.responseType,'text');

        params.init = checkParam(params.init,function(){});

        params.success = checkParam(params.success,function(){});

        params.error = checkParam(params.error,function(){});

        params.cache = checkParam(params.cache,true);

        if(!params.cache) {params.url += "?" + "cacheBust=" + generateCacheBust();}

        request(params.url,"POST",dataToString(params.data),params.init,function(req){

            params.success(formattedResponse(req,params.responseType));

        },params.error);

    };

    return {

        get:get,

        post:post

    };

});

在网络日志 (Firefox) 上,这里是 firebug 显示的 header

请求 header :

POST /explorer/ajax/navigate.php?cacheBust=1412147821832 HTTP/1.1
Host: genortal.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://genortal.com/dashboard.php
Content-Length: 12
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

响应头:

HTTP/1.1 200 OK
Date: Wed, 01 Oct 2014 07:17:01 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.3
Expires: Sat, 01 Jan 2005 00:00:00 GMT
Cache-Control: no-cache, no-store
Pragma: no-cache
Last-Modified: Wed, 01 Oct 2014 07:17:02GMT
Content-Length: 744
Keep-Alive: timeout=5, max=79
Connection: Keep-Alive
Content-Type: application/json

这是我断开互联网连接后得到的标题:

请求 header :

POST /explorer/ajax/navigate.php?cacheBust=1412148166275 HTTP/1.1
Host: genortal.com
Connection: keep-alive
Content-Length: 12
Cache-Control: no-cache
Pragma: no-cache
Origin: http://genortal.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Content-type: application/x-www-form-urlencoded
Accept: */*
Referer: http://genortal.com/dashboard.php
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

响应头:

HTTP/1.1 200 OK
Date: Wed, 01 Oct 2014 07:22:46 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.3
Expires: Sat, 01 Jan 2005 00:00:00 GMT
Cache-Control: no-cache, no-store
Pragma: no-cache
Last-Modified: Wed, 01 Oct 2014 07:22:47GMT
Content-Length: 117
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json

服务器端代码:

<?php
/**
 * Generation Portal
 * Date: 24/9/14
 * Time: 8:59 PM
 */

require_once '../../start_session.php';
require_once '../../libload.php';

use GenerationPortal\Genortal\Accounts\Session;
use GenerationPortal\Genortal\RequestIn;
use GenerationPortal\Genortal\ErrorDictionary\AjaxErrors;
use GenerationPortal\Genortal\AjaxHandler;
use GenerationPortal\Genortal\Explorer\Navigator;
use GenerationPortal\Genortal\Storage\DatabaseLayer;
use GenerationPortal\Genortal\FileSystem\FileSystem;

header("Expires: Sat, 01 Jan 2005 00:00:00 GMT");
header("Last-Modified: ".gmdate( "D, d M Y H:i:s")."GMT");
header("Cache-Control: no-cache, no-store");
header("Pragma: no-cache");

$requestIn = new RequestIn();

$ajaxHandler = new AjaxHandler();

if(!Session::loggedIn()) {

    $ajaxHandler->error('not_signed_in',AjaxErrors::desc('not_signed_in'));

}

if(!$requestIn->paramSet('path')) {

    $ajaxHandler->error('missing_parameters',AjaxErrors::desc('missing_parameters'));

}

$navigator = new Navigator();

try {

    $databaseLayer = new DatabaseLayer();

    $fileSystem = new FileSystem(Session::uid(),$requestIn->param('path'),$databaseLayer);

} catch (\Exception $e) {

    $ajaxHandler->error('server_error',AjaxErrors::desc('server_error'));

}

$ajaxHandler->respond($navigator->parseDirectoryListing($fileSystem));

任何人都可以就这里发生的事情提供快速帮助吗?这是HTTP缓存的作用吗?

最佳答案

您应该为此目的尝试使用缓存无效化。我的意思是传递一个额外的参数,它是可变的,你的 URL 是这样的

www.mydomain.com/navigate.php; //url without cache bust parameter
myRand=parseInt(Math.random()*99999999); 
www.mydomain.com/navigate.php?rand=54321 //url with cache bust parameter

因此在上面的缓存中,您的服务器会将其理解为新请求。

关于javascript - AJAX POST 请求被缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26135860/

有关javascript - AJAX POST 请求被缓存的更多相关文章

  1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  2. ruby - 如何在 Ubuntu 中清除 Ruby Phusion Passenger 的缓存? - 2

    我试过重新启动apache,缓存的页面仍然出现,所以一定有一个文件夹在某个地方。我没有“公共(public)/缓存”,那么我还应该查看哪些其他地方?是否有一个URL标志也可以触发此效果? 最佳答案 您需要触摸一个文件才能清除phusion,例如:touch/webapps/mycook/tmp/restart.txt参见docs 关于ruby-如何在Ubuntu中清除RubyPhusionPassenger的缓存?,我们在StackOverflow上找到一个类似的问题:

  3. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  4. ruby-on-rails - Ruby on Rails 计数器缓存错误 - 2

    尝试在我的RoR应用程序中实现计数器缓存列时出现错误Unknownkey(s):counter_cache。我在这个问题中实现了模型关联:Modelassociationquestion这是我的迁移:classAddVideoVotesCountToVideos0Video.reset_column_informationVideo.find(:all).eachdo|p|p.update_attributes:videos_votes_count,p.video_votes.lengthendenddefself.downremove_column:videos,:video_vot

  5. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  6. ruby - HTTP 请求中的用户代理,Ruby - 2

    我是Ruby的新手。我试过查看在线文档,但没有找到任何有效的方法。我想在以下HTTP请求botget_response()和get()中包含一个用户代理。有人可以指出我正确的方向吗?#PreliminarycheckthatProggitisupcheck=Net::HTTP.get_response(URI.parse(proggit_url))ifcheck.code!="200"puts"ErrorcontactingProggit"returnend#Attempttogetthejsonresponse=Net::HTTP.get(URI.parse(proggit_url)

  7. ruby-on-rails - 获取并发布相同匹配项的请求 - 2

    在我的路线文件中我有:match'graphs/(:id(/:action))'=>'graphs#(:action)'如果是GET请求(工作)或POST请求(不工作),我想匹配它我知道我可以使用以下方法在资源中声明POST请求:post'/'=>:show,:on=>:member但是我怎样才能为比赛做到这一点呢?谢谢。 最佳答案 如果你同时想要POST和GETmatch'graphs/(:id(/:action))'=>'graphs#(:action)',:via=>[:get,:post]编辑默认值可以设置如下match'g

  8. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  9. ruby-on-rails - 如何在 ActionController::TestCase 请求中设置内容类型 - 2

    我试图像这样在我的测试用例中执行获取:request.env['CONTENT_TYPE']='application/json'get:index,:application_name=>"Heka"虽然,它失败了:ActionView::MissingTemplate:Missingtemplatealarm_events/indexwith{:handlers=>[:builder,:haml,:erb,:rjs,:rhtml,:rxml],:locale=>[:en,:en],:formats=>[:html]尽管在我的Controller中我有:respond_to:html,

  10. ruby - 如何测试 (rspec) 花费太长时间的 http 请求? - 2

    如果使用rspec请求花费的时间太长,我该如何测试行为?我正在考虑使用线程来模拟这个:describe"Test"doit"shouldtimeoutiftherequesttakestoolong"dolambda{thread1=Thread.new{#net::httprequesttogoogle.com}thread2=Thread.new{sleep(xxseconds)}thread1.jointhread2.join}.shouldraise_errorendend我想确保在第一次发出请求后,另一个线程“启动”,在这种情况下只是休眠xx秒。然后我应该期望请求超时,因为执

随机推荐