简体   繁体   中英

Problem with ajax only working once

AJAX only works once, i have to reload the page for it to work again. How do i fix this?

echo "<div class='unsubscribe'><a id='us$id' href='javascript:unsubscribe($id);'><img src='/unsubscribe.jpg' alt='unsubscribe' /></a></div>";



function unsubscribe(number)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("us"+number).innerHTML="<img src='/subscribe.jpg' alt='subscribe' />";
    }
  }
xmlhttp.open("GET","/unsubscribe.php?id="+number,true);
xmlhttp.send();
}

Browsers diverge in API for AJAX and it would be wise to use some well maintained library like jQuery to write compliant and easy code. If you dont need the bloat of features you can try other recommendations from this thread.

AJAX Only Javascript Library

move the xmlhttp.open("GET","/unsubscribe.php?id="+number,true); before xmlhttp.onreadystatechange=function() line.

here is the ajax order:

  1. open()
  2. onreadystatechange
  3. send()

Change your HTML : use an onClick handler rather than an href:

<a id='us$id' href="#" onclick="unsubscribe($id);">

This ensures that the action happens on the click, but does not redirect the browser's target page (which is why your function will only fire once at present).

Depending on the layout of your page, you may find the above results in a 'jerk' of the page when the click happens - if so, you can try returning false from the click handler:

<a id='us$id' href="#" onclick="unsubscribe($id); return false;">

I think there is a problem with the names us$id and $id . If you are not using jQuery, then the $ sign is nothing special, it is a plain character. So, us$id and $id are unrelated, $id is just a substring of us$id . So, unsubscribe($id) is called with an undefined argument. If you wanted to replace the image under us$id , then this will not work because getElementById("us"+number) will not find the element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM