2014-02-22 21 views
0

我使用ajax來檢索設置的網址,並從網站的HTML中獲取一條信息。Ajax加載頁面和解析,不能使用ajax中設置的變量?

這很多工作,但是當我嘗試使用我在ajax中設置的變量時,他們仍然未定義。我知道ajax並不是這樣做的最好方式,但我有很短的時間才能完成這項工作,而且這種方法似乎在我嘗試過的所有其他方法中發揮最大作用。

繼承人的代碼,我使用的是:

function getPrice() { 
       alert("Getting Price"); 
       $.ajax({ 
        url: URL, 
        type: "GET", 
        datatype:"html", 
        success: function(result) { 
         $('#holder').html($(result)); 
         var textcontents = $('#holder').find('td').text(); 
         var target = textcontents.split("\n"); 
         Price = target[3]; 
         price = Price; 
         alert(price); 
         return price; 
         } 
        }); 

        db.transaction(updatePrice, successCB, errorCB); 

      } 

價格變量試圖傳遞給updatePrice功能,但這個錯誤與消息SQL錯誤未定義,未定義的,因爲它不會出現要傳遞變量。任何幫助將不勝感激。

回答

0
(function() { 
    var price; //this will be available anywhere within this scope 

    function getPrice() { 
     alert("Getting Price"); 
     $.ajax({ 
      url: URL, 
      type: "GET", 
      datatype:"html", 
      success: function(result) { 
       $('#holder').html($(result)); 
       var textcontents = $('#holder').find('td').text(); 
       var target = textcontents.split("\n"); 
       price = target[3]; // lets set the price variable here 
       alert(price); 
       } 
      }); 

      db.transaction(updatePrice, successCB, errorCB); 
    } 
    // rest of your application code goes here 
}()); 

現在確保你正在過price變量爲updatePrice功能。

+0

謝謝,非常感謝。 – Joooooosh