jquery ajax post, get, javascript ajax post, get 处理

ajax 创建 XMLHttp 对象
IE7 以上的版本都支持 XMLHttpRequest
IE7 以下的用 ActiveXObject

async:true,  // 当false 时,当执行完这个才继续后面的工作, true 时不等这个完成,就直接继续向后执行 默认为 true,即为异步
方法如下:
var xHRObject = false;
if(window.XMLHttpRequest) // XMLHttpRequest 不能带括号
{
    xHRObject = new XMLHttpRequest();
}else if(window.ActiveXObject)
{
    xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
}else
{
    // 异常,不支持
}

ajax 执行过程为:
0:未初始化,尚末调用 open() 方法
1:启动。已经调用 open() 方法,但尚未调用 send() 方法
2:发送。已经调用 send() 方法,但尚未接收到响应
3:接收。已经接收到部分响应数据
4:完成。已经接收到全部响应数据,而且已经可以在客户端使用
以上执行过程可以用 XHR 对象的 readyStatus 属性来获取相应的代码(0, 1. 2, 3, 4)

xhr.open(method, url, bool);
如:
XHR.open("get", "test.php?v=88", false);
XHR.send(null); // send(string)只是用于 post方式, get方式为 null或或者留空
bool 为了false,所以请求是同步的,js 会等服务器响应之后再继续执行.

当接收到响应后,响应数据会自动填充XHR对象的属性。相关属性如下:
responseText:作为响应主体被返回的文本
responseXML:如果响应的内容类型是 "text/xml"或者 "application/xml",这个属性中将保存包含着响应数据的XML DOM 文档
status: 响应的HTTP状态
statusText: HTTP 状态的说明
onreadystatechange: 返回或设置异步请求的事件处理程序
onreadystatechange 示例:
xhr.open();
xhr.onreadystatechange = getFunc;
xhr.send();

function getFunc()
{
    if(xhr.readyState ==1)
    {

    }else if(xhr.readyState == 2)
    {

    }else if(xhr.readyState == 3)
    {

    } .....
}

用 get 方法传递时,IE会产生缓存,所以为了不让其缓存,可以用如下两种方法
1.在 后面加上一个时间的参数,让其一直在更新,如:
xhr.ajax('get', 't.php?t='+Number(new Date)+'&name=lin3615');
2。加入头信息,如:
xhr.get();
xhr.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');

as:

<!DOCTYPE HTML>
<html>
<head>
<meta content="text/html charset=utf-8" />
<title>lin3615</title>

</head>
<body>
<h1>测试内容</h1>
<div id="id1">XX</div>
<div id="id2">222<div>
<div id="id3">333</div>
<div id="id4">4444</div>
<a href="javascript:void(0);" onClick="ok();">Onclick</a>
</body>
</html>
<script type="text/javascript">
   var xmlhttp;
    function ok()
    {

        if(window.XMLHttpRequest)
        {
      xmlhttp = new XMLHttpRequest();
        }else
        {
      xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
        }
        xmlhttp.onreadystatechange = tt;
        xmlhttp.open('get', 'cache.php?id='+Math.random(), true);//异步
        xmlhttp.send();
        alert("xxxxxxxx");
        document.getElementById('id4').innerHTML = xmlhttp.responseText;
    }

function tt()
        {
       if(xmlhttp.readyState== 4 && xmlhttp.status == 200)
            {
         alert("444444");
            }else if(xmlhttp.readyState == 1)
            {
        alert("111111");
            }else if(xmlhttp.readyState == 2)
            {
         alert("222222");
            }else if(xmlhttp.readyState == 3)
            {
         alert("3333333");
            }
        }
</script>
//以上为异步传输,即就是没有等 cache.php处理完成,就直接处理后面的程序,所以在 id = id4中的值为空
// 如果是 xmlhttp.open('get', 'cache.php?id='+Math.random(), false);即同步,则必须等 cache.php执行完成才执行后面的程序,此时 id = id4的值为 cache.php中的输出结束
cache.php
echo 'hi,lin3615';
sleep(10);

-----------------------------------------------------------

jquery ajax post

首先引入 jquery,js 文件;

提交的页面(例:index.html)
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script src="./jquery-1.7.2.min.js"></script>
<script language="javascript">
$(document).ready(function(){
  $("#ok").click(function(){
  // $.post("处理页面", {"属性名":"属性值", "属性名":"属性值"},
  //function(data, status){
  // 其中data 为处理页面返回的结果,status 为成功时返回的信息: "success"
 //  })
  var t1 = document.getElementById("txt").value;
  var t2 = document.getElementById("uu").value;
    $.post("good.php",{'vv':t1,'uu':t2},function(data, status){
     $("#myDiv").html(data);
  alert(status);
    return false; // 防止冒泡
    });
  return false; // 防止冒泡
  });
});

</script>
<body >
<form method="get">
<input type="text" name="vv" id="txt" value="" />
<input type="text" name="uu" id="uu" value="" />
<button id="ok" value="ppp">Button</button>
<div id="myDiv"></div>
</form>
</body>
</html>

good.php文件格式如下:

<?php

print_r($_POST);

// array('vv'=> '', 'uu'=>'')

?>

备注:
"处理的页面",如 process.php 文件,用来接收过来的属性值
属性名:属性值,如 user: 'username'
data:即为处理页面返回返回的数据(即显示)
相当于在 #myDiv 中回显返回的 data 数据

ajax jquery get

首先引入 jquery,js 文件;
提交页面:如 index.html

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script src="./jquery-1.7.2.min.js"></script>
<script language="javascript">
  $(document).ready(function(){
    $('#ok').click(function(){
    var str = document.getElementById("txt").value;

     htmlobj = $.ajax({url:"good.php?id="+str, async:false});
     $("#myDiv").html(htmlobj.responseText);
   return false;
   });
    return false;
  });

</script>
<body >
<form method="get">
<input type="text" name="vv" id="txt" value="" />
<button id="ok" value="ppp">Button</button>
<div id="myDiv"></div>
</form>
</body>
</html>

good.php文件

<?php

print_r($_GET);

?>

备注:
NO.3:表示获取 id = txt 标题里面的内容给变量 str
No.4:表示异步处理,2.php?id=+str, 2.php表示处理的页面,id=+str表示传的 $_GET['id'] = str,回显的数据放在 htmlobj对象中

ajax javascript post

首页页面:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Untitled Document</title>
</head>
<script language="javascript">
function saveUserInfo(){
//获取接受返回信息层
var msg = document.getElementById("msg");
//获取表单对象和用户信息值
var f = document.user_info;
var userName = f.user_name.value;
var userAge   = f.user_age.value;
var userSex   = f.user_sex.value;

//接收表单的URL地址
var url = "2.php";
//需要POST的值,把每个变量都通过&来联接
var postStr   = "user_name="+ userName +"&user_age="+ userAge +"&user_sex="+ userSex;
//实例化Ajax
var ajax = false;
//开始初始化XMLHttpRequest对象
if(window.XMLHttpRequest) { //Mozilla 浏览器
  ajax = new XMLHttpRequest();
  if (ajax.overrideMimeType) {//设置MiME类别
     ajax.overrideMimeType("text/xml");
  }
}
 else if (window.ActiveXObject) { // IE浏览器
   try {
       ajax = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
    try {
   ajax = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {}
 }
}
if (!ajax) { // 异常,创建对象实例失败
  window.alert("不能创建XMLHttpRequest对象实例.");
  return false;
 }
        
//通过Post方式打开连接
ajax.open("POST", url, true);

//定义传输的文件HTTP头信息
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

//发送POST数据
ajax.send(postStr);

//获取执行状态
ajax.onreadystatechange = function() {
   //如果执行状态成功,那么就把返回信息写到指定的层里
   if (ajax.readyState == 4 && ajax.status == 200) {
    msg.innerHTML = ajax.responseText;
   }
}
}
</script>
<body >
<div id="msg"></div>
<form name="user_info" method="post" action="">
姓名:<textarea name="user_name" cols="30" rows="5"></textarea>
年龄:<input type="text" name="user_age" /><br />
性别:<input type="text" name="user_sex" /><br />

<input type="button" value="提交表单" onClick="saveUserInfo()">
</form>

</body>
</html>

提交页面:2.php

print_r($_POST);

ajax javascript get(有个问题就是IE会产生缓存,所以可加相应的参数)

两种方法:

1.加一个时间变量:如 "t.php?t="+new Date()

2.设置时间信息: xml.setRequestHeader("If-Modified-Since","Wed, 26 Feb 1997 08:21:57 GMT");

原文件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>111111</title>
</head>
<script>
function subAjax(){
 var xmlhttp;
 if(window.XMLHttpRequest){
  xmlhttp = new XMLHttpRequest();
 }else{
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange = function(){
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
   document.getElementById("divText").innerHTML = xmlhttp.responseText;
  }
 }
 var txt = document.getElementById("txt").value;
 xmlhttp.open("GET", "good.php?id="+txt, true);
 xmlhttp.send(null);
 return false;
}
</script>
<body>
<form action="" method="get" name="myform" onSubmit="return subAjax()">
<input type="text" id="txt" name="text" value="" /><br />
<input type="submit" name="submit" value="提交" id="submit" />
<input type="reset" name="reset" id="reset" value="重置" />
</form>
<div id="divText">
111
</div>
</body>
</html>

good.php文件:

<?php
//header("Content-type:text/html; charset=gb2312");
echo $_GET['id'];
?>

jquery post 低级用法

$.ajax({
    url:url,
    type: 'post',

 async:true,  // false 时,当执行完这个才继续后面的工作, true 时不等这个完成,就直接继续向后执行 默认为 true,即为异步 
    data:{name: ok, score: 100},
    success:function(data){   // data为 url 中返回的数据
        alert(data);
    }
});

=======

// jquery ajax  之 get 方法, 相当于 e.php?item=$(this).text(),然后 data 就是在 e.php 文件 中输出的数据
/*
$(document).ready(function(){
    $('#letter-e a').click(function(){
        $.get('e.php', {'term': $(this).text()}, function(data){
            $('#dictionary').html(data);
        });
        return false;
    });
});

*/

// jquery ajax 之 post 方法,与 get 一样,只不过是用的是 post 方法而已
/*
$(document).ready(function(){
    $('#letter-e a').click(function(){
        $.post('e.php', {'term': $(this).text()}, function(data){
            $('#dictionary').html(data);
        });
        return false;
    });
});
*/

// 可用 .load() 方法去取代 .post() 方法
/*
$(document).ready(function(){
    $('#letter-e a').click(function(){
        $('#dictionary').load('e.php', {'item': $(this).text()});
            return false;
    });
});

*/

// 用 .serialize()
$(document).ready(function(){
    $('#letter-f form').submit(function(){
        $.get('f.php', $(this).serialize(), function(data){
            $('#dictionary').html(data);
        });
        return false;
    });
});

// 关注请求状态 .ajaxStart() 请求开始,还没有传输数据,.ajaxStop(),最后一次活动请求终止
$(document).ready(function(){
    $('<div id="loading">loading ...</div>')
        .insertBefore('#dictionary')
        .ajaxStart(function(){
            $(this).show();
    }).ajaxStop(function(){
        $(this).hide();
    });
});

/* ajaxComplete() t.php 文件接收为 $_REQUERST['txt']

$(document).ready(function(){
    $('#sub').click(function(){
        var mytxt = $('#userid').val();
        $.get('t.php', {'txt': mytxt}, function(data){
            alert(data);
        });
        $(this).ajaxComplete(function(){
            alert("ok");
        })
        return false;
    });
});
*/
// 可以用 .load 来模仿 .ajaxComplete()事件
$(document).ready(function(){
    $('#sub').click(function(){
        $('.log').load('lin3615.html');
    });
});

低级的 ajax

$('#myId').keyup(function(){
    $.ajax({
        'url': 'seacher.php',
        'data': {'search-text': $(this).val()},
        'dataType': 'json',
        'type': 'get',
        'success': function(data)
        {
            alert(data);
        }
    });
});



原文地址:https://www.cnblogs.com/lin3615/p/3170786.html