2015-12-15 104 views
0

我從XML文件檢索值時遇到問題。 我有一個提醒,它給了我期望的值,但是當我嘗試返回值時,它返回NaN。 在此先感謝。JQuery從xml檢索值

function GetNumberOfSales(fixedScenario) { 
    var result; 
    $.ajax({ 
      type: "GET", 
      url: "values.xml", 
      dataType: "xml", 
      success: function (xml) {   
      $(xml).find("values").each(function() { 
       alert($(this).find(fixedScenario).text()); 
       result = $(this).find(fixedScenario).text(); 
      }); 
     } 
    }); 
    return result; 
} 
+0

爲此提供jsfiddle –

+0

['.parseXML'](http://api.jquery.com/jQuery.parseXML/) –

回答

1

您需要使用:

var $xml = $(xml).parseXML(); 

然後使用上述對象的jQuery的功能:

function GetNumberOfSales(fixedScenario) { 
    var result; 
    $.ajax({ 
    type: "GET", 
    url: "values.xml", 
    dataType: "xml", 
    success: function(xml) { 
     var $xml = $(xml).parseXML(); 
     $xml.find("values").each(function() { 
     alert($(this).find(fixedScenario).text()); 
     result = $(this).find(fixedScenario).text(); 
     }); 
    } 
    }); 

    // This executes before the AJAX call is completed. 
    // This will NEVER work! 
    // Please add the logic that uses the `result` here. 
    return result; 
} 

而且,你不能return從AJAX調用的值,因爲它是異步的。無論你想用服務器響應做什麼,都必須在success函數內完成,而不是在別處。