如何使用ajax将javascript变量发送到php?

时间:2012-01-04 12:55:06

标签: php javascript ajax

场景是,下面是html文件,我想通过它来显示div id =“myDiv”的文本文件的内容。

该文件将由php读取。 php内容如下。 我无法从文本文件中获取内容。请告诉我在ajax部分应该添加什么来纠正程序。

<html>
<head>
<script  type="text/javascript">

function ajaxRequest(tb) {
var xmlhttp;
if (window.XMLHttpRequest)
{
    xmlhttp=new XMLHttpRequest();
}
  xmlhttp.onreadystatechange=statechange()
  {
      if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
      {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      }
  }
xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+tb,true);
xmlhttp.send();
}</script>

</head>

<body>
<div >
       <div id="myDiv">Text from file should come here.</div>
       <button type="button" onclick="ajaxRequest(myfile.txt)">Change Content</button>
</div>
</body>
</html>




Below is the PHP file

<?php
    $tbName = $_GET['tb'];
    $file = "/home/$tbName";
    $f = fopen("$file", "r");
    echo "<ul>";
    while(!feof($f)) {
    $a= fgets($f);


    echo "<li>$a</li><hr/>";

    }
    echo "</ul>";

?>

2 个答案:

答案 0 :(得分:0)

<button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>

请记住在onclick中引用字符串。

这是一个固定版本:

<html>
<head>
<script type="text/javascript">
function ajaxRequest(tb) {
  if (window.XMLHttpRequest){
    var xmlhttp= new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
      if (xmlhttp.readyState==4 && xmlhttp.status == 200){
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }
    }
    xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+ encodeURIComponent(tb),true);
    xmlhttp.send();
  }
}
</script>
</head>
<body>
       <div id="myDiv">Text from file should come here.</div>
       <button type="button" onclick="ajaxRequest('myfile.txt')">Change Content</button>
</body>
</html>

出了什么问题:

  • 测试了XMLHttpRequest的存在,但是函数没有包含在if中,使得它无用。
  • 变量名称有点不匹配 - 仔细检查
  • EncodeURI Component,如下所述
  • 回调函数的正确语法是window.onload = function(){ alert('func!'); }而非window.onload = alert(){ alert('load!'); }

应该是这样,除非PHP脚本有问题,请尝试直接访问URL来测试它。

答案 1 :(得分:0)

修正报价

onclick="ajaxRequest('myfile.txt')"

确保在tb上使用encodeURIComponent()

xmlhttp.open("GET","http://localhost/TBR/getdata.php?tb="+encodeURIComponent(tb),true);

在浏览器中测试您的php页面:http://localhost/TBR/getdata.php?tb=myfile.txt是否提供您想要的数据?

如果是这样测试函数被调用。 (发出警报或调试代码并在函数中放置断点,或者如果浏览器支持,则使用console.debug)

如果函数被调用,那么你的事件处理程序正常工作,如果没有尝试重写它或以不同方式附加它,如onclick =“ajaxRequest('myfile.txt');”虽然我怀疑丢失的分号不是问题所在。

如果调用它,您可以尝试查看是否执行了ajax调用,检查网络流量。任何体面的浏览器都会让你这样做(点击f12并查找网络标签)。如果发出并响应了ajax请求,您应该能够看到请求和响应。

假设一切正常,请确保调用事件ajax事件处理程序。我怀疑这里有一个问题,因为您没有将事件处理程序设置为函数...

xmlhttp.onreadystatechange = function statechange()
{
    if (xmlhttp.readyState==4 && XMLHttpRequestObject.status == 200)
    {
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}

所有这些都使您的数据插入代码无效。