如何缓存从Ajax调用收到的数据?

我想缓存从服务器收到的数据,以便执行最少数量的PHP / MySQL指令。 我知道为$ .ajax()自动设置缓存选项。 但是,即使postdata与之前的调用相同,每次调用$ .ajax()时,我都会看到MySQL指令。 我错过了什么吗? 缓存从服务器接收的数据的最佳方法是什么? 这是我的代码:

var postdata = {'pid':'', 'record_id':this.id}; $.ajax({ type: "POST", url: "get_note.php", data: postdata }).done(function(data){ if (data != '0') { // Add dialog content $('#note_container').html(data); $('#note_container').dialog(); } else { alert(woops); } }); 

这是个主意。 当然,根据您的需要调整它。

 function getAjaxData(){ var $node = $('#note_container'); if ($node.data('ajax-cache').length == 0) { $.ajax({ // do stuff. success: function(data){ // Add dialog content $node.html(data).data('ajax-cache',data).dialog(); } }); } else { $node.html( $node.data('ajax-cache') ).dialog(); } } getAjaxData(); 

我会自己处理缓存:

 // declare this on global scope var ajaxCache = {}; ... if (!ajaxCache[this.id]) { ajaxCache[this.id] = $.ajax({ type: "POST", url: "get_note.php", data: {'pid':'','record_id':this.id} }); } ajaxCache[this.id].done(function(){ if (data != '0') { // Add dialog content $('#note_container').html(data); $('#note_container').dialog(); } else { alert('woops'); } }); 

这样,如果已经发生了具有所述id的请求,则除非将其从缓存中删除,否则不会发出新请求。

你必须添加一个缓存参数,如:

 $.ajax({ ... ... cache : true });