解析XML使用jQuery Ajax请求 [英] parse xml with jquery ajax request
本文介绍了解析XML使用jQuery Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的XML文档:
I have this xml document:
<?xml version="1.0" encoding="utf-8"?>
<root>
<chapter>
<lesson>message 1</lesson>
<lesson>message 2</lesson>
<lesson>message 3</lesson>
<lesson>message 4</lesson>
<lesson>message 5</lesson>
<lesson>message 6</lesson>
<lesson>message 7</lesson>
<lesson>message 8</lesson>
<lesson>message 9</lesson>
<lesson>message 10</lesson>
<lesson>message 11</lesson>
</chapter>
</root>
这是我的code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "numbers.xml",
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("chapter").each(function() {
$(this).find("lesson").each(function() {
$("#dropdownlist").val($(this).text());
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).val().text() + " ";
});
$("#dropdownlist").val(str);
})
.change();
});
});
}
});
</script>
</head>
<body>
<div>
<form id="myform" name="form1" action="" method="get">
<input style="border-style: inset" maxlength="70" size="90" type="text" id="dropdownlist" />
</form>
</div>
<table>
<p style="font-family: 'Monotype Corsiva'" align="right">
chapter
<select style="width: 100px" name="lessons" id="dropdownlist">
<option>lesson_1</option>
<option>lesson_2</option>
<option>lesson_3</option>
<option>lesson_4</option>
<option>lesson_5</option>
<option>lesson_6</option>
<option>lesson_7</option>
<option>lesson_8</option>
<option>lesson_9</option>
<option>lesson_10</option>
<option>lesson_11</option>
</select>
</p>
</table>
</body>
</html>
我的问题是,code堆栈,并告诉我从XML解析只有第一个结果。当我从下拉菜单中选择所有的第一选择是好的,但是当我选择了其他选项栈,并再次给我的第一个。有什么建议么?
My problem is that the code stack and show me only the first result from xml parse. When i choose the first choice from dropdown menu everything it is ok, but when i choose the others options stack and show me the first again. Any suggestions?
推荐答案
试试这个code:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "numbers.xml",
dataType: "xml",
success: function(response) {
$('lesson', response).each(function() {
$("#dropdownlist").append($('<option />').text($(this).text()));
});
}
});
$("select").change(function() {
var str = '';
$(this).find(":selected").each(function() {
str += $(this).text() +' ';
});
$("#dropdownlist").val(str);
}).change();
});
您是每次循环时附加的变化()
触发你的元素。
You were attaching a change()
trigger to your element every time you looped.
这篇关于解析XML使用jQuery Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文