简体   繁体   中英

AJAX request returns entire HTML page instead of just the data I wanted it to echo

I have:

Index.php

      <?php
   if(isset($_POST["id"])){
     echo($_POST["id"]);
   }    
       ?>

JavaScript:

 let xhttp = new XMLHttpRequest();
        xhttp.open("POST", "index.php", true);
        xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
        xhttp.onreadystatechange = function (){
            if(xhttp.readyState == 4 && xhttp.status == 200)
            {
                let result = xhttp.responseText;
                console.log(result)
            }
        }
        xhttp.send("id=195");

But the console prints the whole HTML code for the php page. I thought it should print just the ID.

It sounds like you have other code in index.php, then?

If you only want it to print the ID, add an exit(); command just after it echoes the ID, so that the rest of the script is not processed in that situation. (That's assuming that the PHP code comes before the HTML in the file, of course.)


Ps Most developers tend to separate the PHP which responds to Ajax requests from the PHP which deals with loading HTML pages. This

a) prevents the type of problem you're experiencing,

b) keeps the functionality clean and clear and separate, making unit testing a lot easier, and

c) takes a step to it being more like a fully-fledged API which just deals with data - and can potentially be called from other applications, services or front-ends too, if that's useful.

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