JQuery从xml中检索值

时间:2015-12-15 10:49:24

标签: jquery xml

我在从XML文件中检索值时遇到问题。 我有一个警报,它给了我预期的值,但当我尝试返回值时,它返回NaN。 提前谢谢。

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;
}

1 个答案:

答案 0 :(得分: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函数内完成,而不是在其他地方完成。