Ajax 脚本不工作 getElement

Ajax script not working getElement

我进行了 ajax 搜索 sql,并且在脚本中有一部分我可以定义结果的显示位置。 这是脚本:

<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","getuser.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>

像这样的脚本可以工作并将数据 ind <div> 称为 "txtHint"。现在,我将其更改为 document.getElementsByClassName("right middle").innerHTML = "";document.getElementsByClassName("txtHint").innerHTML = xmlhttp.responseText;,这就是问题所在。在那之后 div my that 中没有显示任何内容,如果我撤消该更改并将 txtHint 放回原处,它就会正常工作。什么是问题?注意,右中是class,txtHint是id.

getuser.php

<?php
$q = $_GET['q'];

$con = mysqli_connect('localhost','root','','mobilni');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"mobilni");
$sql="SELECT * FROM imena WHERE Okrug = '".$q."'";
$result = mysqli_query($con,$sql);
?>
<?php 
while($row = mysqli_fetch_array($result)) {
    ?>
<div class="divmobilni">
<div class="floatright"><img src="images/nokia-lumia-720.jpg" height="66px" width="50px" /></div>
Ime: <div class="imepozadina"><?php echo $row['Ime'];?></div><br />
Okrug: <div class="imepozadina"> <?php echo $row['Okrug'];?></div>
<br />
Telefon: <div class="imepozadina"><?php echo $row['Telefon'];?></div>

<?php } ?>

scipt.js

(function($) {

  $.fn.menumaker = function(options) {

      var cssmenu = $(this), settings = $.extend({
        title: "Menu",
        format: "dropdown",
        breakpoint: 768,
        sticky: false
      }, options);

      return this.each(function() {
        cssmenu.find('li ul').parent().addClass('has-sub');
        if (settings.format != 'select') {
          cssmenu.prepend('<div id="menu-button">' + settings.title + '</div>');
          $(this).find("#menu-button").on('click', function(){
            $(this).toggleClass('menu-opened');
            var mainmenu = $(this).next('ul');
            if (mainmenu.hasClass('open')) { 
              mainmenu.hide().removeClass('open');
            }
            else {
              mainmenu.show().addClass('open');
              if (settings.format === "dropdown") {
                mainmenu.find('ul').show();
              }
            }
          });

          multiTg = function() {
            cssmenu.find(".has-sub").prepend('<span class="submenu-button"></span>');
            cssmenu.find('.submenu-button').on('click', function() {
              $(this).toggleClass('submenu-opened');
              if ($(this).siblings('ul').hasClass('open')) {
                $(this).siblings('ul').removeClass('open').hide();
              }
              else {
                $(this).siblings('ul').addClass('open').show();
              }
            });
          };

          if (settings.format === 'multitoggle') multiTg();
          else cssmenu.addClass('dropdown');
        }

        else if (settings.format === 'select')
        {
          cssmenu.append('<select style="width: 100%"/>').addClass('select-list');
          var selectList = cssmenu.find('select');
          selectList.append('<option>' + settings.title + '</option>', {
                                                         "selected": "selected",
                                                         "value": ""});
          cssmenu.find('a').each(function() {
            var element = $(this), indentation = "";
            for (i = 1; i < element.parents('ul').length; i++)
            {
              indentation += '-';
            }
            selectList.append('<option value="' + $(this).attr('href') + '">' + indentation + element.text() + '</option');
          });
          selectList.on('change', function() {
            window.location = $(this).find("option:selected").val();
          });
        }

        if (settings.sticky === true) cssmenu.css('position', 'fixed');

        resizeFix = function() {
          if ($(window).width() > settings.breakpoint) {
            cssmenu.find('ul').show();
            cssmenu.removeClass('small-screen');
            if (settings.format === 'select') {
              cssmenu.find('select').hide();
            }
            else {
              cssmenu.find("#menu-button").removeClass("menu-opened");
            }
          }

          if ($(window).width() <= settings.breakpoint && !cssmenu.hasClass("small-screen")) {
            cssmenu.find('ul').hide().removeClass('open');
            cssmenu.addClass('small-screen');
            if (settings.format === 'select') {
              cssmenu.find('select').show();
            }
          }
        };
        resizeFix();
        return $(window).on('resize', resizeFix);

      });
  };
})(jQuery);

(function($){
$(document).ready(function(){

$(window).load(function() {
  $("#cssmenu").menumaker({
    title: "Menu",
    format: "dropdown"
  });


$('#cssmenu').prepend("<div id='menu-indicator'></div>");

var foundActive = false, activeElement, indicatorPosition, indicator = $('#cssmenu #menu-indicator'), defaultPosition;

$("#cssmenu > ul > li").each(function() {
  if ($(this).hasClass('active')) {
    activeElement = $(this);
    foundActive = true;
  }
});

if (foundActive === false) {
  activeElement = $("#cssmenu > ul > li").first();
}

defaultPosition = indicatorPosition = activeElement.position().left + activeElement.width()/2 - 5;
console.log(activeElement);
console.log(activeElement.position().left);
console.log(activeElement.width());
indicator.css("left", indicatorPosition);

$("#cssmenu > ul > li").hover(function() {
  activeElement = $(this);
  indicatorPosition = activeElement.position().left + activeElement.width()/2 - 5;
  indicator.css("left", indicatorPosition);
}, 
function() {
  indicator.css("left", defaultPosition);
});

});

});
})(jQuery);

HTML part

<div class="beyondheader"></div>
<div class="header">
<div id='cssmenu'>
<ul>
   <li class='active'><a href='index.html'>Početna</a></li>
   <li><a href='proizvodjaci.html'>Proizvodjači</a></li>
   <li><a href='oglasi.html'>Oglasi</a></li>
   <li><a href='about.html'>O nama</a></li>
</ul>
</div>
</div>

<div class="middle">
<div class="leftmiddle">
<div class="filterl">Okrug:</div>
<div class="filterl"><form>
<select name="okrug" onchange="showUser(this.value)">
  <option value="">Okrug:</option>
  <option value="Raski">Raski</option>
  <option value="Banatski">Banatski</option>
  <option value="Backi">Backi</option>
  <option value="Beogradski">Beogradski</option>
  </select>
</form></div>
</div>
<div id="txtHint">

<div class="divmobilni">


</div>
</div>
</div>

getElementsByClassName always returns 一个数组。你的代码应该是这样的:

document.getElementsByClassName("right middle")[0].innerHTML = "";
document.getElementsByClassName("txtHint")[0].innerHTML = xmlhttp.responseText

getElementsByClassName()returns一组对象,即使只有一个对象class,你也应该称它为索引。例如:

var x=document.getElementsByClassName("txtHint");
x[0].innerHTML = xmlhttp.responseText;

这段代码存在三个问题:

  1. 你要改:

    document.getElementsByClassName("txtHint").innerHTML = xmlhttp.responseText;`
    

    document.getElementsByClassName("txtHint")[0].innerHTML = xmlhttp.responseText;`
    
  2. 您必须有一个带有 txtHint class 的元素。所以也许你忘了更改代码:

    <div id="txtHint">
    

    <div id="txtHint" class="txtHint">
    
  3. 你为什么要改变这个:

    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    }
    

    它重置 txtHint div(使其为空)。