简体   繁体   中英

AJAX request to a php file

I am having problems with a really basic request to a php file from AJAX. I am running all this stuff through XAMPP. What I'm trying to do with this code is to echo the name typed into the textbox once the submit button is clicked and the results to be posted in the div "results". I am doing this to try and weed out errors in another script and so far it hasn't gone too well.

<html> 


<head>
<script type="text/javascript">
function go() {
var request;
 if(window.XMLHttpRequest) {
 request = new XMLHttpRequest();

 }   
     else {

     request = new ActiveXObject("Microsoft.XMLHTTP");
     }
     var uname = document.getElementById("name").value;
     request.onreadystatechange= function() {
         if(request.readyState == 4) {

             document.getElementById("result").innerHTML = response.Text;


             }


        }
        url = "win.php?name="+uname;
        request.open("GET", url, true);
        request.send();
     }
 </script>

   </head>

 <body>
  Name:<input type="textbox"  name="jesus" id="name" />    
  <input type="button" value="Submit"  onlick="go()" />
  <div id ="result"> Result:</div>
   </body>
   </html>



<?php


  $name = $_GET['name'];
  echo $name;





  ?>

You don't have an object called response , you are looking for the responseText property on the request object.

document.getElementById("result").innerHTML = request.responseText;

Also:

  1. avoid using globals
  2. don't send your HTTP request before the target div exists, you run the risk of it still not existing when the response comes back
  3. you probably should check that the HTTP status of the response is 200 (OK) as well as being finished (readyState 4).
  4. Don't put raw user input in URLs, escape it with encodeURIComponent first

使用该document.getElementById("result").innerHTML = response.responseText;

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