2011-10-27 119 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");