简体   繁体   English

将ajax jquery存储到变量中并使用该变量进行访问

[英]Storing ajax jquery into a variable and acessing it with the variable

Can I call jquery ajax from a variable like this ? 我可以从这样的变量调用jquery ajax吗?

var save = $.ajax({
   type: "POST",
   dataType: 'json',
   url: "functions/ajaxInsertCheck.php",
   data: dataString,
   cache: false,
   success: function(response){
      alert(response.a);

   }

 // call ajax jquery
 save

How can I call that request like its a function? 我怎样才能像该函数那样调用该请求? Can anyone help? 有人可以帮忙吗?

You need to use a function . 您需要使用一个函数 Functions encapsulate behavior we will want to invoke in the future. 函数封装了我们将来要调用的行为。 You can pass functions arguments which indicate how you want the function to execute. 您可以传递函数参数 ,这些参数指示您希望函数如何执行。

Functions are typically used when we want to have reusable bits in our code or for code clarity: 当我们想要在代码中具有可重用位或为了代码清晰起见,通常使用函数:

function save(){ // declare a function and call it save
  return $.ajax({ // a return means we're letting people from the outside use it
    type: "POST",
    dataType: 'json',
    url: "functions/ajaxInsertCheck.php",
    data: dataString,
    cache: false,
    success: function(response){
      alert(response.a);
    }
 });
}

Then you can call it from your own code: 然后,您可以从自己的代码中调用它:

save(); // call the save function performing this action.

Note that there are plenty of examples of functions already in your code like alert and $.ajax that were defined by you by the browser and jQuery respectively. 请注意,您的代码中已经有很多功能示例,例如分别由浏览器和jQuery定义的alert$.ajax

If you mean, can you defer execution of the call as you've written it, then no. 如果您的意思是,您可以在编写呼叫时推迟执行该调用,否。 The call is executed immediately. 该调用将立即执行。

Check out the documentation at http://api.jquery.com/jquery.ajax/ - particularly under the heading "The jqXHR Object". http://api.jquery.com/jquery.ajax/上查看文档-特别是在“ jqXHR对象”标题下。 It's different depending on the version of JQuery, but you get back an object that implements the Promise interface. 根据JQuery的版本,它是不同的,但是您将获得一个实现Promise接口的对象。

But using javascript features, you can make a function: 但是,使用javascript功能,您可以创建一个函数:

function saveFunction() {
    $.ajax({
       type: "POST",
       dataType: 'json',
       url: "functions/ajaxInsertCheck.php",
       data: dataString,
       cache: false,
       success: function(response){
          alert(response.a);
       }
    });
}

saveFunction();

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

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