简体   繁体   English

从XML填充jquery表单

[英]populate jquery form from XML

I am attempting to populate a jquery form with data from an XML where the XML has an id that will populate a dropdown in the form and upon selection of an id other form fields will be populated. 我试图用来自XML的数据填充一个jQuery表单,其中XML具有一个ID,该ID将填充该表单的下拉列表,并且在选择ID后,将填充其他表单字段。 BTW I will not be using PHP 顺便说一句我不会使用PHP

My XML 我的XML

<XMLReview>
<plan>
 <planNumber>773</planNumber> 
 <Area>Upper Missouri</Area> 
 <ID>MISSOURI-NUT</ID> 
 <Name>Missouri River</Name> 
 <code>10030101</code> 
 <County>Broadwater</County> 
 <Station_ID>M09MISSR05</Station_ID> 
</plan>
<plan>
 <planNumber>774</planNumber> 
 <Area>Columbia</Area> 
 <ID>FLAT-STILL-TPA-2013</ID> 
 <Name>Sheppard Creek</Name> 
 <Description>- 3A</Description> 
 <code>17010210</code> 
 <County>Flathead</County> 
 <Station_ID>C09SHEPC04</Station_ID> 
</plan>
</XMLReview>

The HTML HTML

<form>
 <input type="button" id="btnxml" value="XML" onclick="getXML()" />

   ID <input type="text" name="ID" id="ID">       
   planNumber<input type="text" name="Name" id="planNumber"> 
   area<input type="text" name="Area" id="Area">
   Name:  <input type="text" name="Name" id="Name">
   Description:  <input type="text" name="Description" id="Description">
   Station ID  <input type="text" name="Station_ID" id="Station_ID">
   <label class="Code-label" for="code">HUC</label>
    <select class="select_code" id="code" name="code" data-iconpos="left" data-icon="grid">
      <option></option>
      <option>  10010001</option>
      <option>  10010002</option>
      <option>  10020001</option>
    </select>
   <label class="county-label" for="County">County</label>
    <select class="select_county" id="County" name="County" data-iconpos="left" data-icon="grid">
     <option></option>
     <option>   Beaverhead </option>
     <option>   Big Horn    </option>
     <option>   Blaine  </option>
    </select>
</form>

The script 剧本

<script>
  function getXML()
 {
 $.get("XMLReview.xml", function(data) {
  $.ajax({
    type: "GET",
    url: "XMLReview.xml",
    dataType: "xml",
    success: function (xml) {
      var select = $('#ID');
        $(xml).find('plan').each(function () {
        var ID = $(this).find('ID').text();
        select.append("<option>" + ID + "</option>");
        $("#ID").change(function () {
            var selectedIndex = $('#ID option').index($('#ID option:selected'));
            var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
                var value = $(this).text();
            });
         });
      }
    }); 
  alert(data);});
 }

</script> 

Unfortunataly this is not working and I don't know why. 不幸的是,这不起作用,我也不知道为什么。 Can anyone help me please 谁能帮我

One or two things: 一两件事:

You are specifying the onclick event inline: 您正在内联指定onclick事件:

<input type="button" id="btnxml" value="XML" onclick="getXML()" />

Why not keep everything in one place -- since you already are using quite a bit of jQuery. 为什么不将所有内容都放在一个地方-因为您已经在使用很多jQuery。 Just add it to the javascript block like this: 只需将其添加到javascript块中,如下所示:

<input type="button" id="btnxml" value="XML" />

and

$('#btnxml').click(function() {
    getXML();
});

Without checking your javascript/ajax code, this construction is wrong: 如果不检查您的javascript / ajax代码,这种构造是错误的:

function getXML(){
    $.get("XMLReview.xml", function(data) {   <<======= REMOVE
        $.ajax({
            type: "GET",
            url: "XMLReview.xml",
            dataType: "xml",
            success: function (xml) {
                var select = $('#ID');
                $(xml).find('plan').each(function () {
                    var ID = $(this).find('ID').text();
                    select.append("<option>" + ID + "</option>");
                    $("#ID").change(function () {
                        var selectedIndex = $('#ID option').index($('#ID option:selected'));
                            var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
                            var value = $(this).text();
                        }); //END $(xml).find.eq.find.each
                    }); //END #ID.change
                }); //END $(xml).find.each
                alert(data);
            } //END AJAX.success fn
        }); //END $.ajax
    }); //END $.get  <<=================================== REMOVE
}

It should look like this: 它看起来应该像这样:

function getXML(){
    $.ajax({
        type: "GET",
        url: "XMLReview.xml",
        dataType: "xml",
        success: function (xml) {
            var select = $('#ID');
            $(xml).find('plan').each(function () {
                var ID = $(this).find('ID').text();
                select.append("<option>" + ID + "</option>");
                $("#ID").change(function () {
                    var selectedIndex = $('#ID option').index($('#ID option:selected'));
                        var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
                        var value = $(this).text();
                    }); //END $(xml).find.eq.find.each
                }); //END #ID.change
            }); //END $(xml).find.each
            alert(data);
        } //END AJAX.success fn
    }); //END $.ajax
}

The extra $.get() wrapper is unnecessary. 不需要额外的$ .get()包装器。

Note that $.ajax() and $.get() and $.post() do the same thing. 请注意, $.ajax()$.get()以及$.post()执行相同的操作。 You are using the more structured $.ajax() construction, which is (IMHO) easier to keep things straight. 您正在使用更具结构化的$.ajax()构造,该构造更易于(IMHO)保持顺直。

$.get() simply hard-codes the type="GET" and $.post() hard-codes the type="POST" $.get()只是硬编码type="GET"$.post()硬编码type="POST"


Also, I haven't done much with the XML dataType, but I strongly suspect that xml -- in the success function of your AJAX code block, in this context: 另外,我对XML数据类型还没有做很多事情,但是我强烈怀疑xml在这种情况下,在您的AJAX代码块的成功函数中:

success: function (xml) {
    //post ajax code here, for eg.
    alert(xml);
}

Is a variable that will contain whatever has been ECHOed/printed/etc from the server side script? 变量是否包含服务器端脚本中已回显/打印/等的内容? I don't believe it's an XML object ... 我不相信这是一个XML object ...

Ok there are kind of a lot of things going on here so I figured a fresh implementation would be easier to understand than a series of corrections (I'll try and note places where your understanding of JavaScript might need some work) First a demo . 好的,这里发生了很多事情,所以我认为一个新的实现比一系列更容易理解(我将尝试指出您对JavaScript的理解可能需要一些工作的地方)。首先是一个演示 Now the JavaScript: 现在的JavaScript:

$('#btnxml').on('click', function() {
    var select = $('#ID'),
        xml = $($.parseXML($('#XMLData').text())),
        plans = xml.find('plan');

    plans.each(function () {
        var ID = $(this).find('ID').text();
        select.append("<option>" + ID + "</option>");
    });

    $("#ID").change(function () {
        var selectedIndex = $('#ID option').index($('#ID option:selected')),
            plan = $(plans[selectedIndex]);

        $('#planNumber').val(plan.find('planNumber').text());
        $('#Area').val(plan.find('Area').text());
        $('#Name').val(plan.find('Name').text());
        $('#Description').val(plan.find('Description').text());
        $('#Station_ID').val(plan.find('Station_ID').text());

        $('#code').val(plan.find('code').text());
        $('#County').val(plan.find('County').text());
    }).trigger('change');
});

And then the HTML 然后是HTML

<script type='text/xml' id='XMLData'>
  <XMLReview>
    <plan>
      <planNumber>773</planNumber> 
      <Area>Upper Missouri</Area> 
      <ID>MISSOURI-NUT</ID> 
      <Name>Missouri River</Name> 
      <code>10030101</code> 
      <County>Broadwater</County> 
      <Station_ID>M09MISSR05</Station_ID> 
    </plan>
    <plan>
      <planNumber>774</planNumber> 
      <Area>Columbia</Area> 
      <ID>FLAT-STILL-TPA-2013</ID> 
      <Name>Sheppard Creek</Name> 
      <Description>- 3A</Description> 
      <code>17010210</code> 
      <County>Flathead</County> 
      <Station_ID>C09SHEPC04</Station_ID> 
    </plan>
  </XMLReview>
</script>
<form>
    <input type="button" id="btnxml" value="XML" /><br/>
    ID <select type="text" name="ID" id="ID"></select><br/>
    planNumber<input type="text" name="Name" id="planNumber"><br/>
    area<input type="text" name="Area" id="Area"><br/>
    Name:  <input type="text" name="Name" id="Name"><br/>
    Description:  <input type="text" name="Description" id="Description"><br/>
    Station ID  <input type="text" name="Station_ID" id="Station_ID"><br/>
    <label class="Code-label" for="code">HUC</label>
    <select class="select_code" id="code" name="code" data-iconpos="left" data-icon="grid">
      <option></option>
      <option>10010001</option>
      <option>10010002</option>
      <option>10020001</option>
      <option>10030101</option>
      <option>17010210</option>
    </select>
    <br/>
    <label class="county-label" for="County">County</label>
    <select class="select_county" id="County" name="County" data-iconpos="left" data-icon="grid">
     <option></option>
     <option>Beaverhead</option>
     <option>Big Horn</option>
     <option>Blaine</option>
    </select>
</form>

First, I made these changes to make this easier to demonstrate in JSFiddle, but they don't necessarily match what your final code will be: 首先,我进行了这些更改,以使其在JSFiddle中更易于演示,但是它们不一定与最终代码相同:

  • I faked the AJAX request (the other answer here gives you a clear explanation of how to properly use jQuery's excellent AJAX helper methods). 我伪造了AJAX请求(此处的另一个答案为您提供了有关如何正确使用jQuery出色的AJAX帮助器方法的清晰说明)。 When rolling this answer into yours you can just assume that all of this is wrapped in a $.get() that fetches your XML remotely. 将这个答案汇总到您的答案中时,您可以假设所有这些都包装在$.get() ,该$.get()可以远程获取XML。
  • I also bound the click handled in JavaScript to $('#btnxml') (this is cleaner, but also because JSFiddle doesn't like onclick attributes that point to named functions), this is not strictly wrong it's just cleaner. 我还将JavaScript中处理的click绑定到$('#btnxml') (这是更干净的方法,但是因为JSFiddle不喜欢指向命名函数的onclick属性),这并不是完全错误的,它只是更干净。

Now for the substantive changes: 现在进行实质性更改:

  • You are really trying to do two things, populate your $('#ID') selector (which was originally a <input type='text'> which is incorrect, in this code I updated to to a <select> , and then after it's populated you are trying to bind a change event handler. You had these steps inside each other, and I separated them back out. Also programmaticly changing a <select> doesn't trigger a change event automatically, so I appended a .trigger('change') at the end. 您实际上是在尝试做两件事,填充您的$('#ID')选择器(最初是不正确的<input type='text'> ,在此代码中,我将更新为<select> )在它填充后,您尝试绑定一个change事件处理程序。您将这些步骤相互.trigger('change') ,而我.trigger('change')它们分开了。另外,以编程方式更改<select>不会自动触发更改事件,因此我附加了.trigger('change')结尾。
  • It also appears that you are attempting to take the child nodes of the selected plan and update the corresponding input with the same name. 看来您正在尝试获取所选计划的子节点,并用相同的名称更新相应的input You could use the .childNodes property but this will include TextNodes for all of the white-space between XML nodes, and rather than trying to filter them out I thought it would be cleaner to just map them individually. 您可以使用.childNodes属性,但这将包括XML节点之间所有空白的TextNodes ,而不是尝试将其过滤掉,我认为单独映射它们会更干净。 This may not work for you if your HTML and XML are constantly being updated but the next point I'm going to make possibly would prevent a totally automatic approach anyways. 如果您的HTML和XML不断更新,那么这可能对您不起作用,但是我接下来要说的那点还是会阻止全自动的方法。
  • Selecting an option based on a value presents some challenges. 基于值选择选项提出了一些挑战。 jQuery is very smart. jQuery非常聪明。 If you have a <select> element with a set of options that don't have value attributes and you try and set that <select> element's .val() by a string of one of those <option> s inside that element it will do the right thing. 如果您的<select>元素带有一组不具有value属性的选项,并且尝试通过该元素内的那些<option>之一的字符串设置该<select>元素的.val() ,它将做正确的事。 However if there are no elements that match that value then it will silently pass over it. 但是,如果没有与该值匹配的元素,则它将以静默方式传递给它。 Your XML has code and County values that do not appear in your HTML. 您的XML具有未出现在HTML中的代码和县值。 I added the missing code values to show you that it is working, but I didn't add them to the County <select> . 我添加了缺少的代码值以向您显示它正在运行,但没有将它们添加到County <select> If you know all of your possible codes and county's and you can update your HTML then this won't be a problem, if instead you want new values to be appended while old values are just selected, then your code will get a little trickier. 如果您知道所有可能的代码和县的代码,并且可以更新HTML,那么这将不是问题,如果您希望在仅选择旧值的情况下附加新值,则代码将变得有些棘手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM