zoukankan      html  css  js  c++  java
  • js高级程序设计AJAX && JSON

    var xhr = createXHR();
    //启动请求
    /**
    * 参数1:要发送的请求类型
    * 参数2:请求的url
    * 参数3:是否异步发送请求的布尔值
    */
    xhr.open("get", "example.php", false);
    //发送请求
    /**
    * 参数:作为请求主体发送的数据,不需要是必须传入null
    */
    xhr.send(null);

    //收到响应后,相应的数据会自动填充xhr的属性
    /**
    * responseText:作为响应主体被返回的文本
    * responseXML:如果响应的类型是“text/xml”或“application/xml”,这个属性中将保存包含着响应数据的XML DOM文档
    * status:响应的HTTP状态
    * 一般来说,可以将HTTP状态代码为200作为成功的标志,此时responseText属性的内容已经就绪
    * 状态代码为304表示请求的资源并没有被修改,可以直接使用浏览器缓存的版本
    * statusText:HTTP状态的说明
    */
    //确保接收到适当的响应
    /*
    xhr.open("get","example.txt",false);
    xhr.send(null);
    */
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
    console.log(xhr.statusText);
    } else {
    console.log("Request was unsuccessful:" + xhr.status);
    }
    /**
    * 发送异步请求时,可以检测XHR对象的readyState属性,该属性表示请求/响应过程的当前活动阶段
    * 属性可取的值:
    * 0:为初始化。尚未调用open()方法。
    * 1:启动。已经调用open()方法,但尚未调用send()方法。
    * 2:发送.已经调用send()方法,但尚未接收到响应。
    * 3:接受。已经接收到部分响应数据。
    * 4:完成。已经接收到全部响应数据
    */
    //只要readyState属性的值有一个值变成另一个值时,都会触发一次readyStateChange事件
    var xhr1 = createXHR();
    xhr1.onreadystatechange = function () { //readyState属性改变时触发
    if (xhr1.readyState == 4) { //发送异步请求完成时
    if ((xhr1.status >= 200 && xhr1.status < 300) || xhr1.status == 304) {
    //请求成功后的HTTP状态代码或者未被修改的缓存的状态
    console.log(xhr.responseText);
    } else {
    console.log("Request was unsuccessful");
    }
    }
    };
    xhr1.open("get", "example.txt", true);
    xhr1.send(null);
    //注意:使用实际的XHR对象实例变量更可靠

    //接收到响应之前可以调用abort()方法来取笑异步请求
    //XHR对象会停止触发事件,而且也不在允许访问任何与响应有关的对象属性
    xhr1.abort();

    //HTTP头部信息
    //使用setRequestHeader()方法可以设置自定义的请求头部信息,不要使用浏览器正常发送的字段名称
    //必须在调用open()方法之后且调用send()方法之前调用setrequestHeader()
    var xhr2 = createXHR();
    xhr2.onreadystatechange = function () {
    if (xhr.readyState == 4) {
    if ((xhr2.state >= 200 && xhr2.state < 300) || xhr.state == 304) {
    console.log(xhr2.responseText);
    } else {
    console.log("Request was unsuccessful:" + xhr.status);
    }
    }
    };
    xhr2.open("get", "example.txt", true);
    xhr2.setRequestHeader("MyHeader", "MyValue"); //注意位置
    //getAllResponseHeaders(); //getAllResponseHeaders()方法则可以取得一个包含所有头部信息的长字符串
    xhr2.send(null);

    //GET请求
    /*
    最常用于向服务期查询某些信息。可以将查询字符串参数追加到URL的末尾。
    对XHR而言,位于传入open()方法的URL末尾的查询字符串必须经过正确的编码才行
    */
    xhr.open("get", "example.php?name1=value1& name2=value2", true);
    //创建辅助向现有URL的末尾添加查询字符串参数
    function addURLParam(url, name, value) {
    url += (url.indexOf("?") == -1 ? "?" : "& "); //判断有无"?"
    url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
    return url;
    }

    var url = "example.php";
    //添加参数
    url = addURLParam(url, "name", "Nicholas");
    url = addURLParam(url, "book", "Profesional Javascript");
    //初始化请求
    xhr.open("get", url, false);
    xhr.send(null);

    //POST请求
    /*
    POST请求应该把数据作为请求的主体提交
    POST请求的主题可以包含非常多的数据,且格式不限
    默认情况下,服务器对POST请求和提交Web表单的请求不会一视同仁
    不过我们可以使用XHR模仿表单提交
    */
    //对表单数据进行序列化处理函数
    function serialize(form) {
    var parts = [];
    var field = null;
    for (var i = 0, len = form.elements.length; i < len; i++) {
    field = form.elements[i];
    switch (field.type) {
    case "select-one":
    case "select-multiple":
    for (var j = 0, optLen = field.options.length; j < optLen; i++) {
    var option = field.options[i];
    if (option.selected) {
    var optValue = "";
    if (option.hasAttribute) {
    //DOM supported browser
    optValue = (option.hasAttribute("value") ? option.value : option.text);
    } else {
    //for IE
    optValue = (option.attribute("value").specified ? option.value : option.text);
    }
    parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue));
    }
    }
    break;
    case undefined: //字段集
    case "file": //文件输入
    case "submit": //提交按钮
    case "reset": //重置按钮
    case "button": //自定义按钮
    break;
    case "radio": //单选按钮
    case "checkbox": //复选框
    if (!field.checked) {
    break;
    }
    /* 执行默认行为 */
    default:
    parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));
    }
    }
    return parts.join("&");
    }

    function submitData() {
    var xhr = createXHR();
    xhr.onreadystatechange = function () {
    if (xhr == 4) {
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
    console.log(xhr.responseText);
    } else {
    console.log("Request was unsuccessful:" + xhr.status);
    }
    }
    };

    xhr.open("post", "postexample.php", true);
    //首先将Content-Type头部信息设置为application/x-www-form-urlencoded
    //就是表单提交时的内容类型
    xhr.setrequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var form = document.getElementById("user-info");
    //以适当的个市创建一个字符串并发送请求
    xhr.send(serialize(form));
    }

    //ie8超时设定
    var xhr = createXHR();
    xhr.onreadystatechange = function (event) {
    try {
    if (xhr.readyState == 4) {
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
    console.log("xhr.responseText");
    } else {
    console.log("Request was unsuccessful:" + xhr.status);
    }
    }
    } catch (ex) {
    //假设由ontimeout事件处理程序处理
    }
    };
    xhr.open("get", "timeout.php", true);
    xhr.timeout = 1000;
    xhr.ontimeout = function () {
    console.log("Request did not return in a second");
    };
    xhr.send(null);

    //跨域请求
    /*
    确保不会再请求和响应中携带cookie,其次是确保未经授权无法访问相应的资源
    */
    //ie的XDomainRequest对象,ie8时引用
    var xdr = new XDomainRequest();
    xdr.onload = function () {
    console.log(xdr.responseText);
    };
    xdr.onerror = function () {
    console.log("An error occurred");
    };
    xdr.timeout = 1000;
    xdr.ontimeout = function () {
    console.log("Request took too long.");
    };
    //xdr.abort(); //终止请求
    xdr.open("get", "http://www.somewhere-else.com/page/"); //只有两个参数,url是绝对地址
    xdr.send(null);
    //为支持POST请求,XGR对象提供了contentType属性
    var xdr = new XDomainRequest();
    xdr.onload = function () {
    console.log(xdr.responseText);
    };
    xdr.onerror = function () {
    console.log("An error occurred");
    };
    xdr.open("get", "http://www.somewhere-else.com/page/");
    xdr.contentType = "application/x-www-form-urlencoded";
    xdr.send("name1=value1 & name2=value2");

    //跨域XHR firefox
    var xhr = createXHR();
    xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
    if ((xhr.readyState >= 200 && xhr.status < 300) || xhr.status == 304) {
    console.log(xhr.responseText);
    } else {
    console.log("Request was unsuccessful:" + xhr.status);
    }
    }
    };
    xhr.open("get", "http://www.somewhere-else.com/page/", true);
    xhr.send(null);


    /*********** JSON ***********/
    //JSON结构
    //属性必须加引号
    var person = {
    "name":"Nicholas C. Zakas",
    "title":"Software Engineer",
    "author":true,
    "age":29
    };
    //JSON是用js中的数组字面量来表示数组
    var myJSONObject = {"bindings":[
    {"ircEvent":"PRIVMSG", "method":"newURI", "regex":"^http://.*"},
    {"ircEvent":"PRIVMSG", "method":"deleteURI", "regex":"^delete.*"},
    {"ircEvent":"PRIVMSG", "method":"randomURI", "regex":"^random.*"}
    ]
    };
    //这些都是纯文本,不是js代码,SON字符串可以传递eval()函数,让其解析并返回一个对象或数组的实例
    //求值为一个数组
    var people = eval(jsonText);
    //访问数据
    console.log(people[0].name);
    people[1].age = 36;
    if (people[0].author) {
    console.log(people[0].name + " is an author");
    }

    //对JSON求值
    var object = eval("(" + jsonText + ")"); //放在一对圆括号中

    //使用Douglas Crockford的JSON解析器
    var jsonText = "(\"name\":\"Nicholas\",\"age\":28,\"author\":true)";
    var object = JSON.parse(jsonText, function (key, value) {
    switch (key) {
    case "age":
    return value + 1;
    case "author":
    return undefined;
    default:
    return value;
    }
    });
    console.log(object.age); //29
    console.log(object.author); //undefined

    //假设addressbook.php会以下面的格式返回JSON数据
    /**
    * [
    * {
    * "name" :"Nicholas C. Zakas",
    * "email":"123456@qq.com"
    * },
    * {
    * "name":"Jim",
    * "email":"321654!qq.com"
    * },
    * {
    * "name":"Jones",
    * "email":"zxczxcqq.com"
    * }
    * ]
    */
    //发送一个Ajax请求取得以上数据,然后在客户端勇士以下代码生成相应的ul元素
    var xhr = createXHR();
    xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
    //解析返回的JSON文本
    var contacts = JSON.parse(xhr.responseText);
    var list = document.getElementById("contacts");
    //遍历生成相应的html
    for (var i = 0, len = contacts.length; i < len; i++) {
    var li = document.createElement("li");
    li.innerHTML = "<a href=\"mailto:" + contacts[i].email + "\">" + contacts[i].name + "</a>";
    list.appendChild(li);
    }
    }
    }
    };
    xhr.open("get", "addressbook.php", true);
    xhr.send(null);

    //向服务器发送JSON数据,使用stringify()方法返回未经缩进的JSON字符串
    /**
    * stringify()
    * @param1:要序列化的对象
    * @param2:可选的替换函数(用于替换未受支持的JSON值)
    * @param3:可选的缩进说明符(可以使每个级别缩进的空格数,也可以是用来缩进的字符)
    */
    var contact = {
    name:"Nicholas",
    age:28,
    author:true
    };
    var jsonText = JSON.stringify(contact);
    console.log(jsonText); //(\"name\":\"Nicholas\",\"age\":28,\"author\":true)

    /*函数和undefined值无法通过JSON表示,包含它们的任何键默认都将被移除。使用stringify()第二个函数参数。对于JSON支持的数据类型,在序列化过程中不会调用这个函数*/
    var jsonText = JSON.stringify([new Function()], function (key, value))
    {
    if (value instanceof Function) {
    return "(function)";
    } else {
    return value;
    }
    }
    ;
    console.log(jsonText); //"[(function)]"

    //使用POST请求将JSON数据发送给服务器
    var xhr = createXHR();
    var contact = {
    name:"Ted",
    email:"123456!qq.com"
    };
    xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
    console.log(xhr.responseText);
    }
    }
    };
    xhr.open("post", "addcontact,php", true);
    xhr.send(JSON.stringify(contact));

  • 相关阅读:
    java 静态和非静态代码块执行顺序
    spring boot 学习
    js中的jQuery Validate增加手机号码验证
    JAVA验证手机号码是否正确
    redis启动报错 var/run/redis_6379.pid exists, process is already running or crashed
    移动端点击a标签拨打电话
    js计算两个日期之间的天数
    JS根据日期获取判断星期几
    JAVA生成订单编号工具类
    JAVA微信支付——微信公众号内支付 代码
  • 原文地址:https://www.cnblogs.com/webFrontDev/p/2753499.html
Copyright © 2011-2022 走看看