dongzantai7570 2012-04-22 04:09
浏览 37
已采纳

无法获取xmlhttprequest发送方法的工作方式

Forgive the simplistic question. I'd like to pass a variable from javascript to php and I understand this can be done with an xmlhttprequest object. So I built a test script to figure out how to do this.

I'm using XAMPP and I placed the following files, main.php and test.php into their proper location in the htdocs folder.

main.php tries to pass a variable to test.php using an xmlhttprequest. test.php simply echos the variable. I then try and display the echoed result in main.php.

When I load main.php in a browser and view source, I expect to see the variable echoed. Instead I see an error message that the variable that was supposed to be passed to test.php is undefined.

Any help would be most welcome.

    <html>
    <head>
    <title>Main</title>

    <script type="text/javascript" src="../scripts/jquery-1.7.1.min.js"></script>

    <script language="javascript" type="text/javascript">

    $(document).ready(function () {

        xmlhttp=new XMLHttpRequest();

        xmlhttp.open("GET","test.php?var1=hello", true);
        xmlhttp.send(null);

        <?php include("test.php"); ?>

    });

    </script>

</head>
<body></body>
</html>

Here is the code in test.php which resides in the same folder as main.php

<?php
$name=$_GET['var1'];
echo $name;
?>
  • 写回答

2条回答 默认 最新

  • doutan2228 2012-04-22 04:16
    关注

    I believe you're running the request in asynchronous mode, so check for ready state change:

    xmlhttp=new XMLHttpRequest(); 
    
    xmlhttp.open("GET","test.php?var1=hello", true); 
    xmlhttp.send(null); 
    
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
       alert(xmlhttp.responseText)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料