重用jquery-ajax调用中传递的'data'

时间:2010-07-14 14:17:55

标签: javascript jquery

我在点击按钮时使用了jquery的.ajax()方法。

我想知道是否有一种方法可以使用我在success()函数中传递给AJAX调用的数据部分的数据。

这是我的代码,

$.ajax({
  url: //my URL here..
  type: 'POST',
  data:{
    projDets : projDetailsArray,
  },
  datatype:'html',
  error: function(){
    alert('Error loading Project Information');     
  },
  success: function(html){
    //I wanted to re-use 'projDets' that I'm passing in the 
    //'data' part of my code..                  
  }
});

任何帮助将不胜感激。

由于

2 个答案:

答案 0 :(得分:0)

Pritish - 一种快速而肮脏的方法是将json数组存储在jquery .data()对象中,然后根据需要检索它。

1,将data:元素设置为命名数组:

// set 'outside' of the $ajax call
var projDetailsData = {projDets : projDetailsArray};
// now store it in a div data object
$("#targetDiv").data("myparams", projDetailsData);

// the data part of the $ajax call
data: projDetailsData,

再次检索它:

// get the value stored and call the $ajax method again with it
var projDetailsDataCopy = $("#targetDiv").data("myparams");

值得一试啊!

吉姆

[edit] - 另外,您当然可以将数组存储在模块级vaiable -yuk中! :)

答案 1 :(得分:0)

您可以将$.ajax参数包装在闭包中,将“data”值设置为局部变量,然后将其引用为“data”值和“success”函数内部:

$.ajax(function() {
  var data = {
    projDets: projDetailArray
    // ...
  };
  return {
    url: // your URL here..
    type: 'POST',
    data: data,
    datatype:'html',
    error: function(){
      alert('Error loading Project Information');     
    },
    success: function(html){
      // just reference "data" here!          
    }
  };
}());
相关问题