doudizhu2222 2019-02-18 16:00
浏览 45
已采纳

从XML实现CSS自动完成

I am trying to parse XML in PHP and then put it as an object in JavaScript to Materialize CSS autocomplete.

I tried to parse it in PHP and put it as an object in JavaScript with json_encode($array) But it didn't work. Autocomplete shows just numbers.

You have to put data as an object in "data". And it must be as "string": 'http://url' the URL is for a thumbnail. But I want it as "string": null. So there won't be a thumbnail.

This is a sample from Materialize CSS documentation: https://materializecss.com/autocomplete.html

  $(document).ready(function(){
    $('input.autocomplete').autocomplete({
      data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
      },
    });
  });

My XML file:

<tittle>

<topic>
<name>PHP</name>
</topic>

<topic>
<name>JS</name>
</topic>

<topic>
<name>CSS</name>
</topic>

</tittle>

My code:

<!DOCTYPE html>
<html lang="en" >

<head>
 <meta charset="UTF-8">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
 <link rel='stylesheet' href='https://fonts.googleapis.com/icon?family=Material+Icons'>  
</head>

<body>

    <div class="row">
    <div class="col s12">
      <div class="row">
        <div class="input-field col s12">
          <i class="material-icons prefix">textsms</i>
          <input type="text" id="autocomplete" class="autocomplete">
          <label for="autocomplete">Autocomplete</label>
        </div>
      </div>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>



  <?php

  $xml = simplexml_load_file("xml.xml");

  $array = array();

  foreach($xml->topic as $topic)
  {
    $array[] = $topic->name;  
  }

  ?>


    <script >
    var array = <?php echo json_encode($array); ?>;
    console.log(array); 

  $(function () {
  $('input.autocomplete').autocomplete({
    data: array     

  });
});

</script>  
</body>  
</html>

An output of console.log(array);:

The autocomplete is displaying just numbers (0-2). I think those numbers are array indexes.

I think I must change the array structure to "string_from_array": null

Is there any way how to do it? Thank you for response

  • 写回答

3条回答 默认 最新

  • duan1226 2019-02-18 16:07
    关注

    You can change line

    $array[] = $topic->name;
    

    to

    $array[$topic->name] = $topic->name;
    

    that should solve your problem, but not best way to do that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器