Parsing XML using JQuery, need to find by attribute name
I am trying to parse some XML data to display in a basic web page. The XML is the following:
<response>
<variable name = "Input1">False</variable>
<variable name = "Input2">False</variable>
<variable name = "Input3">False</variable>
<variable name = "Input4">False</variable>
<variable name = "Input5">False</variable>
<variable name = "Input6">False</variable>
<variable name = "Input7">False</variable>
<variable name = "Input8">False</variable>
</response>
I have some code which is display that but currently I get all 8 variables show in 1 text area.
$(document).ready(function()
{
$.ajax({
type: "GET",
//To change controller, please chnage the IP below.
url: "http://172.20.2.17/query/variable?Input1&Input2&Input3&Input4&Input5&Input6&Input7&Input8",
dataType: "xml",
success: parseSystem
});
})
//Parse System XML Response
function parseSystem(xml)
{
$(xml).find("response").each(function()
{
$("#Input1").append($(this).find("variable").text())
$("#Input2").append($(this).find("variable").text())
$("#Input3").append($(this).find("variable").text())
$("#Input4").append($(this).find("variable").text())
$("#Input5").append($(this).find("variable").text())
$("#Input6").append($(this).find("variable").text())
$("#Input7").append($(this).find("variable").text())
$("#Input8").append($(this).find("variable").text())
});
What I would is that Input1 in the XML is linked to #Input1 in the HTML开发者_开发技巧 and so forth.
Thank you for your time, it is truly appreciated.
$(xml).find("response").each(function()
{
$("#Input1").append($(this).find("variable[name=Input1]").text())
$("#Input2").append($(this).find("variable[name=Input2]").text())
$("#Input3").append($(this).find("variable[name=Input3]").text())
$("#Input4").append($(this).find("variable[name=Input4]").text())
$("#Input5").append($(this).find("variable[name=Input5]").text())
$("#Input6").append($(this).find("variable[name=Input6]").text())
$("#Input7").append($(this).find("variable[name=Input7]").text())
$("#Input8").append($(this).find("variable[name=Input8]").text())
});
but there is a more flexible function:
$(xml).find("response").each(function(){
$(this).find("variable").each(function(){
var id = $(this).attr("name");
$("#"+id).append($(this).text())
});
});
$(xml).find('response').each(function (index, element) {
var $element = $(element);
var $variables = $('variable', $element);
$variables.each(function (index, variable) {
var $variable = $(variable);
var controlId = $variable.attr('name');
var text = $variable.text();
var $control = $('#' + controlId);
$control.append(text);
});
});
精彩评论