繁体   English   中英

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

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

我可以从这样的变量调用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

我怎样才能像该函数那样调用该请求? 有人可以帮忙吗?

您需要使用一个函数 函数封装了我们将来要调用的行为。 您可以传递函数参数 ,这些参数指示您希望函数如何执行。

当我们想要在代码中具有可重用位或为了代码清晰起见,通常使用函数:

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);
    }
 });
}

然后,您可以从自己的代码中调用它:

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

请注意,您的代码中已经有很多功能示例,例如分别由浏览器和jQuery定义的alert$.ajax

如果您的意思是,您可以在编写呼叫时推迟执行该调用,否。 该调用将立即执行。

http://api.jquery.com/jquery.ajax/上查看文档-特别是在“ jqXHR对象”标题下。 根据JQuery的版本,它是不同的,但是您将获得一个实现Promise接口的对象。

但是,使用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