2011-10-27 120 views
2

在发布之前,我已经通读过,但我仍不清楚如何实现这一目标。 我收到一个xml文件并设置了一些变量,我如何访问ajax成功之外的所有变量以用于其他函数?

$.ajax({ 
    type: "POST", 
    url: getProductList, 
    data: reqProductXML, 
    dataType: "xml", 
    contentType: "text/xml; charset=\"utf-8\"", 
    success: function (data) { 
     $(xml).find('product').each(function() { 
      var productID = $(this).find('id').text(); 
      var productName = $(this).find('name').text(); 
      var productCurrency = $(this).find('currency').text(); 
      var productDescription = $(this).find('description'); 
      var sipAccess = $(this).find('sipAccess'); 
      var skypeAccess = $(this).find('skypeAccess'); 
      var localAccess = $(this).find('localAccess'); 
      var rechargeable = $(this).find('rechargeable').text(); 

      $('#urProductSelect').append("<option value='" + productID + "'>" + productName + "</option>"); 
     }); 
    } 
}); //End ajax 

    // I need to use the variable out here.... 
    $('#urProductSelect').change(function() {...}); 

回答

0

你必须采取其中的变量被定义范围的照顾,因为你的AJAX success功能的所有变量属于该范围内定义的变量,使函数外部定义的任何其它功能赢得了”能够“看见”那些变量,你可以在一个范围内将它们定义在success函数之外,其他任何函数都可以像“全局范围”那样“看到”它们,但这很麻烦。看看这本书,它会告诉你有关范围的一些很好的例子,并关闭太:

http://jqfundamentals.com/book/index.html#example-2.44

1

在一个地方定义变量,使得它们在两者的功能范围, 如

var productID; 

内$就用它们作为

productID = $(this).find('id').text(); 
0

您可以更改例如var productIDwindow.productID以使其成为全球。请记住在使用全局变量时要小心,因为命名问题可能会发挥作用。

0
var productID, productName, productCurrency, productDescription, sipAccess, skypeAccess, localAccess, rechargeable; 
$.ajax({ 
    type: "POST", 
    url: getProductList, 
    data: reqProductXML, 
    dataType: "xml", 
    contentType: "text/xml; charset=\"utf-8\"", 
    success: function (data) { 
     $(xml).find('product').each(function() { 
      productID = $(this).find('id').text(); 
      productName = $(this).find('name').text(); 
      productCurrency = $(this).find('currency').text(); 
      productDescription = $(this).find('description'); 
      sipAccess = $(this).find('sipAccess'); 
      skypeAccess = $(this).find('skypeAccess'); 
      localAccess = $(this).find('localAccess'); 
      rechargeable = $(this).find('rechargeable').text(); 

      $('#urProductSelect').append("<option value='" + productID + "'>" + productName + "</option>"); 
     }); 
    } 
}); //End ajax 

    // I need to use the variable out here.... 
    $('#urProductSelect').change(function() {...}); 
1

我认为最好创建回调函数:

$.post(site_url+"admin/jx_get_group_attibutes", {product_id:id}, function(rdata) { 

      if(rdata.status == 'success') { 
       print_link_products(rdata); // callback function 
      } 
      else { 
       alert(rdata.result); 
       return false; 
      } 
     }, "json");