H
H
hagen17782014-12-22 19:52:36
JavaScript
hagen1778, 2014-12-22 19:52:36

304 Not modified. How to cache ajax requests?

There is a backend on Yii2. The controller checks before responding:

$behaviors['httpCache']=[
            'class' => 'yii\filters\HttpCache',
            'only' => ['index','test'],
            'lastModified' => function ($action, $params) {
                    $q = new \yii\db\Query();
                    return $q->from('user')->max('updated_at');
                },
        ];

If the response has not changed, then the browser returns the cached response.
We raised the application in Angular, where we implemented the following:
$scope.linkto = function() {

            $http.get("http://yii-application/frontend/web/users?access-token=1234567", {crossDomain:true, xhrFields: {withCredentials:true}})
                .success( function (data) {
                    console.log(data);
                    $scope.news = data;
                })
                .error(function(jqXHR, textStatus, errorThrown) {
                    console.log("error " + textStatus);
                })
        }
        $scope.linkto();

And html:
<div ng-controller="TabController">
    <button ng-click="linkto()">clickme</button>
</div>

If the function is executed when the page is loaded, then everything works fine - the request is checked, if nothing has changed, 304 Not modified is returned. If it has changed, then we get a new answer, respectively, and the time to receive a response increases.
But if you click on the button that calls the same function, then these conditions are not met and 200 OK from cache always comes. Even if the answer changes. Here is such a hitch ...
Help me figure it out

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
haiku, 2014-12-23
@haiku

cache: false put in $http.get? You can add a random number to the request every time, ETag and use.
https://docs.angularjs.org/api/ng/service/$http
If you set the default cache to false then only requests that specify their own custom cache object will be cached. From there.

H
hagen1778, 2014-12-23
@hagen1778

Headings are different. But the function is the same

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question