2012-09-15 160 views
0

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

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> 

test.php的

<?php echo "hello"; ?> 

回答

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> 

test.php的

<?php echo "hello".$_GET["q"]; ?> 
0

在我看来就像你有你的JavaScript语法错误。你试图从xmlhttpresponseText但你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(); 
} 
+0

谢谢。很好的与'xmlhttp'搭档,但我试过了你的代码,它仍然没有响应点击。 –

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

以及chan把它弹到

ajaxRequest.responseText(); 
+0

谢谢。我的访问者中只有3%似乎使用IE的旧版本,所以现在我只是专注于让它工作,但我认为在我有事情的时候排除这种情况并不会有什么坏处。 –