2010-07-14 45 views
1

我在按钮单击上使用jquery的.ajax()方法。重复使用在jquery-ajax调用中传递的'data'

我想知道是否有一种方法可以使用我在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..     
    } 
}); 

任何帮助将不胜感激。

由于

+1

“编辑35秒前,尼克Craver” - > 5月以及不打扰回答...尼克将很快发布:D – 2010-07-14 14:22:15

+1

@ILMV - 太繁忙的工作,但他只需引用'projDetailsArray' :) – 2010-07-14 14:23:51

+0

“编辑2分钟前,尼克Craver” - > dum de dum! – 2010-07-14 14:24:45

回答

0

你可以包裹$.ajax参数在封闭,设立了“数据”值作为一个局部变量,然后引用它既为“数据”的价值和“成功”函数内部:

$.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!   
    } 
    }; 
}()); 
+0

谢谢,这工作得很好! – Pritish 2010-07-14 15:12:50

0

Pritish - 一个快速和肮脏的方法是存储在一个jquery。数据()对象JSON数组,然后检索它作为必需的。元素命名阵列:

1,设置数据

// 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"); 

值得一试,也许!

吉姆

[编辑] - 也,你当然可以存储在模块级vaiable -yuk数组! :)

+0

当我尝试在success()函数中尝试使用alert(projDetailsArrayCopy)打印出来时,我得到'undefined'.. – Pritish 2010-07-14 14:34:18

+0

哦,对不起,我以为你想保存和恢复数组作为参数在$ ajax方法中。我想因为关闭,你将无法从成功函数中访问数组。很抱歉对于这个误会。 – 2010-07-14 14:36:54

+0

也许,你可以添加一个额外的参数到成功函数,即成功:function(html,projDetailsData){然后用它的方式 - 没有?? – 2010-07-14 14:42:54