简体   繁体   中英

Alerting string using document.getElementById().innerHTML

I'm trying to alert a string, using document.getElementById().innerHTML, but it's alerting the code of the whole page, instead of the string inside the div. I need it to alert '121'. What am I doing wrong?

<script type = "text/javascript"> 

function getUrban(pageNum, stopAt, gotoUrl) {

var currentPage = "currentPage";
$.ajax({
           type: "POST",
           url: gotoUrl,
           data: { pageNum : pageNum },
           error: function(xhr,status,error){alert("error");},
           success:function(data) {
           document.getElementById("output").innerHTML = data;
           currentPage = document.getElementById("output").innerHTML;
           },
           complete:function(data) {
           alert(currentPage);
           } //end of complete:function(data)

      });

} //end of function getUrban(pageNum)

getUrban(121,422,"test.php");

</script>

<div id = "output"></div>

The full code of the whole page, plus some more code about setting the width.

121

121

$pageNum = $_POST['pageNum'];
echo $pageNum;

Since you're using jQuery to do the ajax why don't you use jquery for everything else also.

$('#output').text();

Will get only the text inside the div. Not the html elements as well.

It drives me crazy to see people using jQuery and have document.getElementById('id') in their code. You do realize that $('id') will get the same element but with jQuery wrapper so you can use jQuery functions on it. And it's so much shorter to type.

<script type = "text/javascript"> 

function getUrban(pageNum, stopAt, gotoUrl) {

$.ajax({
           type: "POST",
           url: gotoUrl,
           data: { pageNum : pageNum },
           error: function(xhr,status,error){alert("error");},
           success:function(data) {
               $("#output").html(data);
           },
           complete:function(data) {
               alert($('#output').text());
           } //end of complete:function(data)

      });

} //end of function getUrban(pageNum)

getUrban(121,422,"test.php");

</script>

<div id = "output"></div>

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