$.ajax() call, only on updation

2019-07-04 07:10发布

I am reading a xml using $.ajax() request.

$.ajax({
    type: "GET",
    async: false,
    url: "../../../ErrorMessages.xml",
    dataType: "xml",
    success: function (xml) {
       $(xml).find("*[Name='" + Field + "']").each(function () {
          message = $(this).find(Rule).text();
       });
    }
});

I want to make the call only when, the resource ErrorMessages.xml is updated. else use the browser cache.

3条回答
女痞
2楼-- · 2019-07-04 07:19

make a global var named "updateTimeStamp" and put the updatetimestamp into the xml. then find the timestamp when you do the ajax request and compare it to your saved ipdateTimeStamp. if it is bigger then do what you need to do and if not do nothing

查看更多
Ridiculous、
3楼-- · 2019-07-04 07:28

Look here: http://jquery14.com/day-01/jquery-14

Etag support was enabled in jQ 1.4, so you could use it.

查看更多
我命由我不由天
4楼-- · 2019-07-04 07:34

The browser won't know if ErrorMessages.xml has been updated on the server. It has to issue a request to check if the file has been modified.

You may want to set the ifModified option to true in your jQuery $.ajax() request, since this is set to false by default:

$.ajax({
  type: "GET",
  ifModified: true,
  async: false,
  url: "../../../ErrorMessages.xml",
  dataType: "xml",
  success: function (xml) {
     // ..
  }
});

Quoting from the jQuery.ajax() documentation:

ifModified (Boolean)

Default: false

Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.

As long as your web server supports the Last-Modified header, then the first request to the XML would look something like this:

GET /ErrorMessages.xml HTTP/1.1
Host: www.example.com

HTTP/1.1 200 OK
Last-Modified: Wed, 06 Oct 2010 08:20:58 GMT
Content-Length: 1234

However, subsequent requests to the same resource will look like this:

GET /ErrorMessages.xml HTTP/1.1
Host: www.example.com
If-Modified-Since: Wed, 06 Oct 2010 08:20:58 GMT

HTTP/1.1 304 Not Modified

If the web server finds that the file has been modified since the If-Modified-Since header date, it will serve the file normally.

查看更多
登录 后发表回答