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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大