码迷,mamicode.com
首页 > Web开发 > 详细

(JS/JQ)与Ajax

时间:2015-04-12 16:14:37      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

JS与Ajax(异步JS和XML):

1.XMLHttpRequest对象的常用方法:

open()准备请求   send()传送请求   abort()取消请求

readyState(请求状态码):0(未开始)、1(开启)、2(已传送)、3(接收中)、4(已载入) 

status(HTTP请求状态码):404(找不到文件)、200(OK)

onreadystatechange:请求状态改变时会被调用函数引用

responseText:服务器返回的纯文本字符串

responseXML:服务器返回的xml格式对象

2.创建请求对象 function createRequest()

function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");  //针对IE浏览器
} catch (failed) { request = null; } } } return request; }

得到请求对象:request = createRequest();

设置请求路径与请求数据:var url = "register.php";
                                  var requestData = "username=" + escape(document.getElementById("username").value);  //POST请求

配置请求:request.open("GET/POST",url,true(异步)/false(同步))

配置回调函数:request.onreadystatechange = displayDetails;

设置请求首部:request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //POST请求

发送请求:request.send(null); //GET请求

              request.send(requestData); //POST请求

创建回调函数:function displayDetails()

例:

function displayDetails() {
  if ((request.readyState == 4) || (request.status == 200) ){
      detailDiv = document.getElementById("description");
      detailDiv.innerHTML = request.responseText;
  }
}

 JQ与Ajax:

1.$.get(URL,callback);

例:$.get("url"function(data) { alert(”data“) });

2.$.post(URL,data,callback);

例:$.post("url", { max: ‘jq, name: ‘eezz }, function(data) { alert(“data”) });

3.$.ajax

jQuery.ajax({
                type: "POST",
                url: "url",
                data: "max=jq &name=eezz",
dataType: "json",
success: function(msg) {alert(msg);} }); $.ajax方法参数详解:http://blog.sina.com.cn/s/blog_4f925fc30100la36.html

 

(JS/JQ)与Ajax

标签:

原文地址:http://www.cnblogs.com/duanyiyi/p/4419598.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!