简体   繁体   中英

ajax get request in javascript without forms through XMLHttpRequest

How do i make an ajax get request like www.example.com/example.php?d=a in javascript? I've tried:

xmlhttp.open("GET","www.example.com/example.php?d=a",true);
xmlhttp.send();

Can someone provide me a working example? Thanks.

Like that.

Although if you mean http://www. etc etc, then you do need to remember the http:// part of the URL.

Beware the same origin policy and see ways to work around it .

If you really want to use GET, here is the code:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","the_page_to_send_request_to.someFileFormat",true);
xmlhttp.send();

Sure :)

This function will make a (POST) request with wahtever data you like ( str ), to wherever you like ( phplocation ). The xmlhttp.responseText is whatever the server sends back :)

<script type="text/javascript">
function submitForm(str, phpLocation)
{
  var xmlhttp;
  if (window.XMLHttpRequest)
    xmlhttp=new XMLHttpRequest();
  else
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

  xmlhttp.onreadystatechange=function()
  {
    if(xmlhttp.readyState<4)
    {
      //i'm not ready yet. Do stuff.....
    }
    if(xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      //Now I'm ready. Do stuff with this: xmlhttp.responseText;
    }
  }
  xmlhttp.open("POST", phpLocation, true);
  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  xmlhttp.send("str=" + encodeURIComponent(str));
}
</script>

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