将ajax jquery存储到变量中并使用变量访问它

时间:2015-01-11 11:40:56

标签: javascript jquery ajax

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

如何将该请求称为函数?有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

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

当我们希望在代码中具有可重用位或代码清晰度时,通常使用函数:

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.

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

答案 1 :(得分:0)

如果你的意思是,你能否在你写完电话时推迟执行电话,那么不。呼叫立即执行。

查看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();