简体   繁体   English

AJAX请求到php文件

[英]AJAX request to a php file

I am having problems with a really basic request to a php file from AJAX. 我对AJAX对php文件的真正基本请求有问题。 I am running all this stuff through XAMPP. 我正在通过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". 我要用此代码执行的操作是,在单击“提交”按钮并将结果发布到div“结果”中后,回显键入到文本框中的名称。 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. 您没有一个名为response的对象,而是在request对象上寻找responseText属性。

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 不要在目标div存在之前发送HTTP请求,否则,当响应返回时,您可能会仍然没有HTTP请求
  3. you probably should check that the HTTP status of the response is 200 (OK) as well as being finished (readyState 4). 您可能应该检查响应的HTTP状态是否为200 (确定)以及是否已完成(readyState 4)。
  4. Don't put raw user input in URLs, escape it with encodeURIComponent first 不要将原始用户输入放在URL中,请先使用encodeURIComponent对其进行转义

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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