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

How to send javascript variable to php using ajax?

本文关键字:变量 php javascript 发送 何使用 ajax      更新时间:2023-09-26

的场景是,下面是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>";
?>

修复引号

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

确保在上面使用encodeuriccomponent ()

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;
    }
}

你的数据插入代码不工作

<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组件,如下所述
  • 回调函数的正确语法是window.onload = function(){ alert('func!'); }而不是window.onload = alert(){ alert('load!'); }

应该就这样了,除非PHP脚本有问题,请直接访问URL进行测试。