js ajax

来源:互联网 发布:中国联通云数据公司 编辑:程序博客网 时间:2024/05/21 01:46
POS请求:
var xmlhttp;
    if(window.XMLHttpRequest==XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }else{
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
     
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
   
                      //回调函数,在此可以将后台传递的值,显示页面
        }
    };
    xmlhttp.open("POST", "url", true);//url 为要跳转的页面
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");//post请求设置参数时使用
    xmlhttp.send("optionValue=12");设置要传递的参数


GET请求:
var xmlhttp;
    if(window.XMLHttpRequest==XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }else{
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
     
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
   
                      //回调函数,在此可以将后台传递的值,显示页面
        }
    };
//url 为要跳转的页面 传递参数demo_get2.asp?fname=Bill&lname=Gates
    xmlhttp.open("GET", "url", true);
    xmlhttp.send();设置要传递的参数

GET 还是 POST?

与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。

然而,在以下情况中,请使用 POST 请求:

  • 无法使用缓存文件(更新服务器上的文件或数据库)
  • 向服务器发送大量数据(POST 没有数据量限制)
  • 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠


异步 - True 或 False?

AJAX 指的是异步 JavaScript 和 XML(Asynchronous JavaScript and XML)。

XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true:

xmlhttp.open("GET","ajax_test.asp",true);