简体   繁体   中英

why is my javascript script running when the page loads and not with onclick?

So below is my script that I want to run when I click a button on the screen. Basically use AJAX to query my database for more results. Problem is, I am VERY new to Javascript and this script runs whenever the page loads rather than when I click the button that is supposed to call it.


<script type="text/javascript">
function next_ten_results()
{
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("main").innerHTML=xmlhttp.responseText;
    }
  }
var page = "<?php echo $page_count; ?>";
alert('the city of ' + page + '!');
var name = "<?php echo $sql_name; ?>";
var rest_location = "<?php echo $sql_location; ?>";
xmlhttp.open("GET","another_ten_results.php?location="+rest_location+"&rest_name="+name+"&page="+page,true);
xmlhttp.send();
}
</script>  

Thanks for reading guys! I'm sure I've made a simple mistake like I need to wait for the document to be ready or something but as I said, I am VERY new. Any help and advice is appreciated.

Cheers!

EDIT: The code that calls this function in case it is needed...even though the code runs without it:

if($num_rows > 9){
      echo '<onclick="next_ten_results_NOT()" class="button next" id="button_next" >Page 2</a>'; }

EDIT (2): For future reference, the problem (as Cody described above) is that I forgot the <a... before the onclick event. This is what caused the code to be run somehow. After changing that, the javascript query worked as planned. The error was actually in the HTML.

Cheers!

For those who visit this looking for an answer:

Your HTML which calls the javascript function is invalid. There are no tags which start with <onclick ... . We can tell by the ending tag </a> that this should be a link.

Replacing <onclick with <a onclick would fix the issue.

Moving my answer to an answer instead of the comments where it was originally:

You're echoing '<onclick="next_ten_results_NOT()" class="button next" id="button_next" >Page 2</a>'; which is creating a tag called . You're missing the <a , which means it's an invalid tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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