使用JQuery / AJAX来填充XML文件的下拉菜单。 [英] Using JQuery/AJAX to populate a drop-down menu with XML file.
问题描述
我有一个下拉菜单,我需要从XML文件填充。
这里是我尝试使用的脚本:
$ $ p $ $(document).ready(function(){/ / load jQuery 1.5
function loadfail(){
alert(Error:Failed to read file!);
}
function parse(document){
$(document).find(menuItem)。each(function(){
var optionLabel = $(this).find('text')。text();
var optionValue = $(this).find('value')。text();
$('。opening')。append(
'< option value =''+ optionValue +'> '+ optionLabel +'< / option>'
);
});
}
$ .ajax({
url:'http ://ourwebserver/Online%20App/jobTitles.xml',//带有我们的数据的文件名 - 链接已被重命名
dataType:'xml',//我们将读取的文件类型
成功:解析,//完成读取文件时调用的函数名称
错误:loadfail //读取失败时调用的函数名称
});
});
以下是xml文件中的示例:
<菜单>
< menuItem>
<值> 612< /值>
< text> CLERK-CMH HOS HIM< / text>
< / menuItem>
< menuItem>
<值> 1632< /值>
< text> FAM PRACT-CMH CLN Southside Medical< / text>
< / menuItem>
这里是html代码包含下拉列表我试图填充:
< strong>所需位置< / strong>
< / select>
我没有收到错误消息,但我也没有收到任何数据来填充菜单。
我也试过了这个链接的代码/解决方案:
使用xml文件填充下拉菜单
,并得到类似的结果,没有错误,但没有数据。
感谢您的帮助。 使用类选择器( .opening
)而不是ID( #opening
)来查找< select>
元素。在 parse
函数中使用 $('#opening')
应该可以正常工作。
I have a drop-down menu that I need to populate from an XML file. Here is the script I am trying to use:
$(document).ready(function(){ // load jQuery 1.5
function loadfail(){
alert("Error: Failed to read file!");
}
function parse(document){
$(document).find("menuItem").each(function(){
var optionLabel = $(this).find('text').text();
var optionValue = $(this).find('value').text();
$('.opening').append(
'<option value="'+ optionValue + '">' + optionLabel + '</option>'
);
});
}
$.ajax({
url: 'http://ourwebserver/Online%20App/jobTitles.xml', // name of file with our data - link has been renamed
dataType: 'xml', // type of file we will be reading
success: parse, // name of function to call when done reading file
error: loadfail // name of function to call when failed to read
});
});
Here is a sample from the xml file:
<menu>
<menuItem>
<value>612</value>
<text>CLERK-CMH HOS HIM</text>
</menuItem>
<menuItem>
<value>1632</value>
<text>FAM PRACT-CMH CLN Southside Medical</text>
</menuItem>
And here is the html code that contains the drop down I am trying to populate:
<strong>Position(s) Desired</strong>
<select name="opening" size="5" multiple="multiple" id="opening">
</select>
I'm not getting an error message, but I'm also not getting any data to populate in the menu.
I have also tried the code/solution at this link: populating a drop down menu with xml file and had a similar outcome, no errors, but no data.
Thanks in advance for your help.
You're using a class selector (.opening
) rather than the ID (#opening
) to find the <select>
element. Using $('#opening')
in your parse
function should work as expected.
这篇关于使用JQuery / AJAX来填充XML文件的下拉菜单。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!