0

单击图像时,我想将名为 john 的 div 的内容更改为 php 文件的输出。我敢肯定这很简单,但我找不到合适的例子。这是我的代码:

function ajaxFunction(){
                var ajaxRequest;
                    ajaxRequest = new XMLHttpRequest();
                ajaxRequest.onreadystatechange = function(){
                    if(ajaxRequest.readyState == 4){
                        document.getElementById("john").innerHTML=xmlhttp.responseText;
                    }
                }
                ajaxRequest.open("GET", "test.php", true);
                ajaxRequest.send(null); 
            }

html

<img class='cross' src='images/cross.png' onclick="ajaxFunction();">
<div id='john'>john</div>

测试.php

<?php echo "hello"; ?>
4

3 回答 3

0

我可以建议跨浏览器/版本,使用:

var ajaxRequest = getXMLHttpRequest();

接着,

function getXMLHttpRequest() {
    var re = "nothing";
    try {re = new window.XMLHttpRequest();} catch(e1) {};
    try {re = new ActiveXObject("MSXML2.XMLHTTP.4.0");} catch(e) {};
    try {re = new ActiveXObject("Msxml2.XMLHTTP");} catch(e2) {};
    try {re = new ActiveXObject("Microsoft.XMLHTTP");} catch(e3) {};
    try {re = new ActiveXObject("MSXML2.XMLHTTP.3.0");} catch(ex) {};
    if (re != "nothing") {return re;}
    else {return null;};
};

以及将其更改为

ajaxRequest.responseText();
于 2012-09-15T09:42:09.403 回答
0

我已经设法用下面的代码解决了它。在从 php 文件中获取“hello”后,此代码还会返回元素的 ID。

<script language="javascript">
            function calldislike(str){
                if (str==""){
                  document.getElementById("john").innerHTML="";
                  return;
                  }
                xmlhttp=new XMLHttpRequest();
                xmlhttp.onreadystatechange=function(){
                    if (xmlhttp.readyState==4 && xmlhttp.status==200){
                    document.getElementById("john").innerHTML=xmlhttp.responseText;
                    }
                }
                xmlhttp.open("GET","test.php?q="+str,true);
                xmlhttp.send();
            }
        </script>

<img src='images/cross.png' onclick="calldislike(this.id);" id='3'>
<div id='john'>john</div>

测试.php

<?php echo "hello".$_GET["q"];  ?>
于 2012-09-16T09:30:26.420 回答
0

在我看来,您的 javascript 有语法错误。您试图从中获取responseTextxmlhttp但您XMLHttpRequest的存储在 ajaxRequest

尝试这个

function ajaxFunction(){
    var ajaxRequest = new XMLHttpRequest();
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
                document.getElementById("john").innerHTML=ajaxRequest.responseText;
            }
        }
    ajaxRequest.open("GET", "test.php", true);
    ajaxRequest.send(); 
}
于 2012-09-15T09:17:52.937 回答