简体   繁体   English

使用jQuery,如何存储对$ .ajax函数的调用结果以供重新使用?

[英]Using jQuery, how can I store the result of a call to the $.ajax function, to be re-used?

Thanks for reading this. 感谢您阅读本文。

I imagine this is really a javascript question, and my title probably does not get at the heart of what I am trying to do, but I want to store the result of my ajax request in a global variable. 我认为这确实是一个JavaScript问题,我的标题可能不是我想做的事情的核心,但是我想将我的Ajax请求的结果存储在全局变量中。 This would allow me to test the var before making the ajax call...and avoid repeated ajax calls for the same data. 这将允许我在进行ajax调用之前测试var ...,并避免对相同数据重复进行ajax调用。 I need to be able to pass the variable name from the click event down through the populateSelect function into the ajaxCall function. 我需要能够将click事件中的变量名通过populateSelect函数向下传递到ajaxCall函数中。

It seems like I could pass a function as a parameter, but I have not been able to make that work. 似乎我可以将函数作为参数传递,但是我无法使它起作用。

I like to include working examples in my questions, but in this case the latency in the call to the server is part of the problem. 我希望在问题中包含一些工作示例,但是在这种情况下,服务器调用的延迟是问题的一部分。

Thanks 谢谢

$('#getSelectOptions').bind("click", function() {
 populateSelect(this);
});

function populateSelect(whatWasClicked) {
 var thisSelect = $(whatWasClicked).parents("div").find("select") ;

 var before = function() { $(loading).show() ;  } ;
 var complete = function() { $(loading).hide() ;  } ;
 var data = {'_service' : 'myService', '_program' : 'myProgram' } ;
 var error = function(){alert("Error"); } ;
 var success = function(request) { $(thisSelect).html(request) ; };
 var waitTime = 20000 ;

 ajaxCall(thisSelect, waitTime, before, complete, data, success, error ) ;
}

function ajaxCall(elementToPopulate, waitTime, whatToDoBeforeAjaxSend,
                  whatToDoAfterAjaxSend, dataToSendToTheServer, 
                  whatToDoAfterSuccess, whatToDoAfterError) {
 $.ajax({   
  type: "post", 
  url: "http://myURL/cgi-bin/broker",   
  dataType: "text", 
  data: dataToSendToTheServer, 
  timeout: waitTime, 
  beforeSend: whatToDoBeforeAjaxSend, 
  error: whatToDoAfterError(request),
  success: whatToDoAfterSuccess(request)
 });
}

EDIT Further education in how to write a good question... I should have mentioned that I call populateSelect to populate multiple selects..so I need way to reference the results for each select 编辑关于如何编写一个好问题的进一步教育...我应该提到我调用populateSelect来填充多个选择..所以我需要一种方法来引用每个选择的结果

It looks like in the example you gave, you only have one type of AJAX request, POST ed to the same URL with the same data every time. 看起来在您给出的示例中,您只有一种AJAX请求,每次都将POST发送到具有相同数据的相同URL。 If that's the case, you should just need something like : 如果是这样,您应该只需要以下内容:

var brokerResponse = null;  // <-- Global variable

function populateSelect(whatWasClicked) {
 var thisSelect = $(whatWasClicked).parents("div").find("select") ;

 if (!brokerResponse) {  // <-- Does an old response exist? If not, get one...
   var before = function() { $(loading).show() ;  } ;
   var complete = function() { $(loading).hide() ;  } ;
   var data = {'_service' : 'myService', '_program' : 'myProgram' } ;
   var error = function(){alert("Error"); } ;

   var success = function(request) {  // <-- Store the response before use
      brokerResponse = request; 
      $(thisSelect).html(brokerResponse);
   };
   var waitTime = 20000 ;

   ajaxCall(thisSelect, waitTime, before, complete, data, success, error ) ;
 }
 else {   // <-- If it already existed, we get here.
   $(thisSelect).html(brokerResponse);  // <-- Use the old response
 }
}

If you have multiple possible items for whatWasClicked which each need a different AJAX response cached, then you need to have some string with which to identify whatWasClicked , and use that to store multiple values in your global variable. 如果whatWasClicked有多个可能的项目,每个项目都需要缓存一个不同的AJAX响应,那么您需要具有一些字符串来标识whatWasClicked ,并使用该字符串将多个值存储在全局变量中。 For example, if you have a unique id on whatWasClicked , this would work: 例如,如果在whatWasClicked上具有唯一的id ,则可以使用:

var brokerResponse = {}; // Global variable is a simple object

function populateSelect(whatWasClicked) {

 var whatWasClickedId = $(whatWasClicked).attr('id'); // Get the unique ID
 var thisSelect = $(whatWasClicked).parents("div").find("select") ;

 if (!brokerResponse[whatWasClickedId]) {  // Check that ID for a response
   var before = function() { $(loading).show() ;  } ;
   var complete = function() { $(loading).hide() ;  } ;
   var data = {'_service' : 'myService', '_program' : 'myProgram' } ;
   var error = function(){alert("Error"); } ;
   var success = function(request) {

      brokerResponse[whatWasClickedId] = request; // Using ID
      $(thisSelect).html(brokerResponse);
   };
   var waitTime = 20000 ;

   ajaxCall(thisSelect, waitTime, before, complete, data, success, error ) ;
 }
 else {
   $(thisSelect).html(brokerResponse[whatWasClickedId]); // Etc...
 }
}

jQuery has a $.data method which you can use to store/retrieve items related to any element on the page. jQuery具有$ .data方法,您可以使用该方法存储/检索与页面上任何元素相关的项目。

//e.g. create some object
var inst = {};
inst.name = 'My Name'

var target = $('#textbox1');

//save the data
$.data(target, 'PROP_NAME', inst);

//retrieve the instance
var inst =  $.data(target, 'PROP_NAME');

JavaScript's scoping is such that if you just declared a global variable, you should be able to access it from within the ajax success function and the click function as well. JavaScript的作用域是这样的:如果您只是声明了全局变量,则应该能够从ajax成功函数和click函数中访问它。

var _global_holder = null;
$('#getSelectOptions').bind("click", function() {
 if(_global_holder==null) { whatever }
 populateSelect(this);
});

function populateSelect(whatWasClicked) {
 if(_global_holder !== null) {
    whatever
  } else { whatever else }

 ajaxCall(thisSelect, waitTime, before, complete, data, success, error ) ;
}

function ajaxCall(elementToPopulate, waitTime, whatToDoBeforeAjaxSend,
                  whatToDoAfterAjaxSend, dataToSendToTheServer, 
                  whatToDoAfterSuccess, whatToDoAfterError) {
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM