带有selectize.js的列表框和XML文件中的数据

时间:2017-04-10 23:34:04

标签: jquery xml selectize.js

我正在尝试在HTML中创建一个包含列表框,注释框和提交按钮的简短表单。该表单允许一个人从列表框中选择最多7个项目,然后留下关于他/她的选择的评论。列表框中的项目本身来自XML文件,该文件与html,php,js和css文件位于同一服务器上。

从XML文件填充列表框,其余表单正常工作。但是,一旦我尝试将列表框与selectize.js结合使用,我就会遇到问题。 Selectize.js本身正在工作,我可以改变列表框,定义可以选择的项目的最大数量等。但列表框的选项突然缺失。就好像XML文件的项目不再正确加载一样。一旦我禁用selectize.js,选项就会回来。

如果这是一个非常基本甚至是重复的问题,我会提前道歉。我对jQuery不太满意,并且从各种来源将代码拼凑在一起。我也尝试通过谷歌搜索类似的问题大约一天找到帮助,但到目前为止没有运气。所以非常感谢任何帮助。

这是我的代码。

的index.php

<?php
     if($_POST['submit'] == "Submit") {

     $errorMessage = "";
     if(empty($_POST['select-songs'])) {
          $errorMessage .= "<li>You forgot to select a song!</li>";
     }

     $log = "";

     foreach ($_POST['select-songs'] as $song) {
          $log .= $song . ",";
     }

     $log .= $_POST['comment'];

     // $songs = $_POST['select-songs'];
     // $comment = $_POST['comment'];

     if(!empty($errorMessage)) {
          echo("<p>There was an error with your form:</p>\n");
          echo("<ul>" . $errorMessage . "</ul>\n");
     } else {
          $fs = fopen("mydata.txt","a");
          fwrite($fs,$log . "\n");
          fclose($fs);
          header("Location: thankyou.html");
          exit;
     }
 }
 ?>

 <html>
      <head>
           <title>Fav5 Song Selector</title>
           <meta charset="UTF-8">
           <!-- jQuery libraries -->
           <script src="libraries/jquery-3.2.0.min.js"></script>
           <script src="libraries/selectize.min.js"></script>

           <!-- scripts -->
           <script language="javascript" type="text/javascript" src="ui.js"></script> <!-- include the reload.js file -->

           <!-- stylesheets -->
           <link rel="stylesheet" href="style.css">
           <link rel="stylesheet" href="selectize.css">
      </head>

      <body>
           <h1>Fav5 Demo UI</h1>
           <form action="index.php" method="post">
                <select id="songLib" name="songLib[]" class="demo-default">
                     <option value="" disabled selected hidden>Select a maximum of 7 songs from your playlist</option>
                </select>

                </br>

                <textarea name="comment" rows="5 "cols="25"></textarea>

                </br>

                <input type="submit" name="submit" value="Submit" />
           </form>
      </body>
 </html>

ui.js

 $(document).ready(function(){
      $.ajax({
           type: 'GET',
           url: 'songs.xml',
           dataType: 'xml',
           success: function(xml){
                $(xml).find('song').each(function() {
                     $('#songLib').append(
                     '<option>' +
                          $(this).find('title').text() +
                     '</option>'
                );
           });
      }
      });

      $('#songLib').selectize({
           delimiter: ',',
           persist: false,
           maxItems: 7
      });
 });

1 个答案:

答案 0 :(得分:1)

好的,我找到了解决问题的方法。

我无法从原始问题中获得selectize.js与jQuery / AJAX一起工作。但结果是selectize.js确实有自己的方式将数据导入列表框。而不是以XML格式提供我的数据,我不得不使用JSON。

如果有人遇到同样的问题,这是代码。

<强> HTML

<?php
    if($_POST['submit'] == "Submit") {
        $errorMessage = "";
        if(empty($_POST['songLib'])) {
            $errorMessage .= "<li>You forgot to select a song!</li>";
        }
        $log = "";
        foreach ($_POST['songLib'] as $song) {
            $log .= $song . ",";
        }
        $log .= $_POST['comment'];
        if(!empty($errorMessage)) {
            echo("<p>There was an error with your form:</p>\n");
            echo("<ul>" . $errorMessage . "</ul>\n");
        } else {
            $fs = fopen("mydata.txt","a");
            fwrite($fs,$log . "\n");
            fclose($fs);
            header("Location: thankyou.html");
            exit;
       }
    }
?>

<html>
    <head>
        <title>Fav5 Song Selector</title>
        <meta charset="UTF-8">
        <!-- jQuery libraries -->
        <script src="libraries/jquery-3.2.0.min.js"></script>
        <script src="libraries/selectize.min.js"></script>
        <!-- scripts -->
        <script language="javascript" type="text/javascript" src="ui.js"></script>  <!-- include the reload.js file -->
       <!-- stylesheets -->
       <link rel="stylesheet" href="style.css">
       <link rel="stylesheet" href="selectize.css">
    </head>

    <body>
        <h1>Fav5 Demo UI</h1>
        <form action="index.php" method="post">
            <select id="songLib" name="songLib[]" class="demo-default" placeholder="Select a maximum of 7 songs from your playlist"></select>
            </br>
            <textarea name="comment" rows="5 "cols="25"></textarea>
            </br>
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

<强> JS

$(document).ready(function(){
    $('#songLib').selectize({
        valueField: 'title',
        labelField: 'title',
        searchField: ['artist','title'],
        options: [],
        maxItems: 7,
        preload: true,
        plugins: ['remove_button', 'restore_on_backspace'],
        delimiter: ',',
        sortField: [
            {
                field: 'artist',
                direction: 'asc'
            },
            {
                field: '$score'
            }
        ],
        load: function(query, callback) {
            $.ajax({
                url: 'songs.json',
                type: 'GET',
                dataType: 'json',
                data: {
                    title: query,
                    artist: query,
                },
                error: function() {
                    console.log("fail");
                    callback();
                },
                success: function(res) {
                    console.log("success");
                    console.log(res);
                    callback(res);
                }
            });
        },
        render: {
            option: function(item, escape) {
                return '<div>'
                + escape(item.artist) + ' - '
                + escape(item.title)
                + '</div>';
            },
            item: function(item, escape) {
                return '<div>'
                + escape(item.artist) + ' - '
                + escape(item.title)
                + '</div>';
            }
        }
   });
});

<强> JSON

[
    {"artist": "Simon & Garfunkel","title": "Mrs. Robinson"},
    {"artist": "Simon & Garfunkel","title": "The Boxer"},
    {"artist": "Crosby, Stills, Nash & Young","title": "Almost Cut My Hair"},
    {"artist": "Queen","title": "Another One Bites the Dust"},
    {"artist": "Queen","title": "Don't Stop Me Now"},
    {"artist": "CCR","title": "I Heard It Through the Grapevine"},
    {"artist": "Iggy Pop","title": "The Passenger"},
    {"artist": "Roy Orbinson","title": "In Dreams"},
    {"artist": "Scorpions","title": "Wind Of Change"},
    {"artist": "CCR","title": "Lookin' Out My Backdoor"},
    {"artist": "The Who","title": "Behind Blue Eyes"},
    {"artist": "Dexys Midnight Runners","title": "Come On Eileen"},
    {"artist": "Neil Young","title": "Heart Of Gold"},
    {"artist": "Neil Young","title": "Old Man"},
    {"artist": "Buffulo Springfield","title": "Stop Children What's That Sound"},
    {"artist": "Pink Floyd","title": "Wish You Were Here"},
    {"artist": "Leatherbag","title": "On Down the Line"},
    {"artist": "Negative Lovers","title": "Faster Lover"},
    {"artist": "Crowded House","title": "Take the Weather With You"},
    {"artist": "Crowded House","title": "Don't Dream It's Over"},
    {"artist": "Townes Van Zandt","title": "Dead Flowers"},
    {"artist": "Polo And Pan","title": "Canopee"},
    {"artist": "Polo And Pan","title": "Plage Isolee"},
    {"artist": "Polo And Pan","title": "Dorothy"},
    {"artist": "Polo And Pan","title": "Rivolta"}
]