jQuery - 基于变量参数查找xml子项

问题描述 投票:0回答:1

我正在创建一个应用程序,将在线表单转换为各种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()中的text参数,而不是在switch中设置updozens案例,我尝试了几种方法,下面是几个例子......

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语句,过滤返回函数,你命名它。希望有人可以回答这个问题,理想情况下只需要一段非常简单的代码。

javascript jquery ajax xml arguments
1个回答
0
投票

感谢Ryan Wilson回答了这个问题,如果有人遇到这个问题,这里有答案......

$('#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();

  //This code finds a single xml node using the argumentVar variable
  var outputVar = $(data).find('coursecode:contains(' + argumentVar + ')').children('description').text();

  //The outputVar is output as text in the outputText field as according to whatever argument the user entered into argumentText
  $('#outputText').val(outputVar);

 },
 error: function(){
 }  
}); //ajax is closed
}); //click function is closed
© www.soinside.com 2019 - 2024. All rights reserved.