【发布时间】:2018-08-14 20:16:00
【问题描述】:
我正在创建一个应用程序,将在线表单转换为各种 PDF 表单以减轻管理负担。我正在使用 XML 文件,以便用户可以输入课程代码,并且表单会自动填充其一些数据以填写课程信息,但是对于下面的代码,我只是使用测试文件先弄清楚。
用户将在文本输入中输入课程代码并单击按钮以调用 Ajax 以读取 xml 并创建变量以填充表单。我浏览了几十个教程和论坛,似乎无法解决我的问题 - 我需要根据输入的课程代码过滤子节点,但我只能通过在js 文件,当我尝试使用变量参数时它不起作用,我尝试了很多不同的方法。
HTML...
<html>
<head><title>XML Reader</title></head>
<body>
<input type="text" id="argumentText">
<input type="button" id="button" value="process">
<input type="text" id="outputText">
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
XML...
当我可以让 jQuery 工作时,最终会有更多的课程代码和子节点
<?xml version="1.0"?>
<course type="array">
<coursecode>CWI416D01F
<description>Signmaking L2</description>
</coursecode>
<coursecode>CWI490D01F
<description>Business Admin L2</description>
</coursecode>
<coursecode>CWA061D01S
<description>Dental Nurse L3</description>
</coursecode>
</course>
我的 jQuery...
请注意,下面的代码确实有效,但创建的 outputVar 根本不使用 argumentVar...
$('#button').click(function(){
$.ajax({
url: 'test.xml',
type: 'GET',
dataType: 'xml',
success: function(data){
//an argument is taken from the argumentText field
var argumentVar = $("#argumentText").val();
//Doing it this way works
var outputVar = $(data).find('coursecode:contains(CWI416D01F)').children('description').text();
//The outputVar is output as text in the outputText field, in this case "Signmaking L2"
$('#outputText').val(outputVar);
},
error: function(){
}
}); //ajax is closed
}); //click function is closed
但我希望 outputVar 将 argumentVar 作为 contains() 中的文本参数,而不必在 switch 中设置数十个案例,我尝试了几种方法,下面是几个示例...
var outputVar =
//Attempt 1
$(data).find('coursecode:contains(argumentVar)').children('description').text();
//Attempt 2
$(data).find('coursecode:contains('"+argumentVar+"')').children('description').text();
//Attempt 3 & 4 (I added an ID into each xml coursecode tag for this attempt)
$(data).find('coursecode[id="argumentVar"]').children('description').text();
$(data).find('coursecode[id=argumentVar]').children('description').text();
我什至尝试了许多其他不同的方法,例如尝试解析、if 语句、过滤返回函数,等等。希望有人可以回答这个问题,最好是用一个非常简单的sn-p代码。
【问题讨论】:
-
您是否像尝试 2 一样尝试过,但删除了变量周围的单引号://尝试 2 $(data).find('coursecode:contains(' + argumentVar + ')').children ('描述').text();
-
aannndd... 就像它一样有效!哈哈。我不敢相信我在这个问题上花了几个小时,你就这样解决了。每当我在其他论坛上看到尝试 2 时,他们都会按照我的方式进行操作,我可能下意识地认为 contains 中的单引号会抵消 find 中的引号。谢谢你的及时回复哥们,你是最棒的!
-
太棒了。很高兴我能帮助你。有第二双眼睛看代码总是很不错的,有时最小的事情可能是最大的问题。
标签: javascript jquery ajax xml arguments