2013-10-08 32 views
2

我试图从xml显示值到表单。这是唯一的HTML页面。

例如 config.xml中有<xml><name>abc</name>....</xml> 和HTML表单有<form><input id="name"></form>

做到这样的,我是试过用ajax()取config.xml文件的内容或得到()函数 然后解析xml然后在html表单上显示这些值。

$(function() { 
    var content; 
    $.ajax('config.xml', { 
     dataType: 'text', 
     success: function (data) { 
      content = data; 
      alert(data); 
     } 
    }); 
}); 

var $inputs = $('#report_form :input'); 

$inputs.each(function (index) { 
    var inputid = $(this).attr('id'); 
    alert(inputid); 
    alert(content); 
    var xml = content, 
     xmlDoc = $.parseXML(xml), 
     $xml = $(xmlDoc), 
     $title = $xml.find(inputid); 
    alert($title.text()); 
    text = $title.text(); 
    $('#' + inputid).val(text); 
}); 

我已经在$阿贾克斯()的地方有

$.get("config.xml", function(data) { 
    xml = data; 
    alert(xml);//Do stuff with data here 
}); 

尝试; 现在我怀疑在执行这个$ .get()/ $。ajax()时,是否只在xml解析器之后执行。

我如何在xml解析之前执行这个$ .get()/ $。ajax()。

+4

它被XML解析之前执行。你的XML解析发生得太早。 ajax是异步的。 –

+1

调用函数从成功函数中解析xml。或者,看看承诺(http://api.jquery.com/promise/) –

+0

这就是你的代码执行的方式:1:define content var。 2:发送ajax请求。 3:迭代输入并解析xml内容。 4:收到xml内容。正如你所看到的,3发生在4之前,这是因为ajax是异步的。将3移到ajax回调的内部,它会在正确的时间发生。 –

回答

2

地方你的回调函数的代码..所以它获得的执行,当数据被检索

$.get("config.xml", function(data) { 
    // what ever here will be executed after the data has returned 
    xml = data; 
    alert(xml);//Do stuff with data here 


    $inputs.each(function (index) 
    { 
     var inputid=$(this).attr('id');alert(inputid); 
     alert(content); 
     var xml = content, 
     xmlDoc = $.parseXML(xml), 
     $xml = $(xmlDoc), 
     $title = $xml.find(inputid); 
     alert($title.text()); 
     text=$title.text(); 
     $('#'+inputid).val(text); 
    }); 
}); 
0

AJAX调用将没有直接回应。但是当它的时候,代码将在它的回调函数里执行(在你的情况下为success)。

就像setTimeout将运行回调,而不是暂停代码。

setTimeout(function {alert("hello")}, 500); 
alert("I will run before timeout!"); 

您将不得不将您的代码放入success回调中。除此之外的其他代码将在ajax成功发送并检索数据之前运行。


$.get("config.xml", function(data) { 
    $inputs.each(function (index) { 
     // The code is now placed inside the callback and will be successfully ran when ajax has completed. 
     var inputid = $(this).attr('id'); 
     var xmlDoc = $.parseXML(data); 
     var text = $(xmlDoc).find(inputid).text(); 
     $('#'+inputid).val(text); 
    }); 
});