正在缓存AJAX POST请求

AJAX POST requests being cached

本文关键字:POST 请求 AJAX 缓存      更新时间:2023-09-26

在我的web应用程序上,我正在向url /navigate.php发送POST请求。它正常工作。

问题是,这个web应用程序应该也可以脱机工作。当由于连接问题无法完成请求时,我将显示一个通知,当问题得到解决时,用户可以再次同步。

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

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

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

我在url上附加了一个缓存中断(new Date().getTime()),但没有任何更改。收到的请求仍有200个。

我尝试从服务器(PHP/Ubuuntu)发送以下标题:

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选项,并将其设置为false。但我想它也会做同样的事情,在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 显示的标题

请求标头:

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

以下是我断开互联网连接时得到的标题:

请求标头:

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

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

问题不在于代码、浏览器或HTTP缓存。问题出在我的操作系统上。即使在我强行断开连接后,连接也没有断开。我通过重新启动桌面解决了这个问题。

为浪费你的一点时间向每一个人道歉!谢谢