ajax异步扩展,AJAX 扩展 异步请求数据的几种方法-jquery篇

1.jquery的 load(url,data,function(response,status,xmlHttp)) url :请求的服务器地址 ,data(向服务器传递的参数:1-》get传值,直接在url上拼接需要传递的参数此时data参数不需要,服务器那边用$_GET取值,2-》post传值,在data里传递一个json的数据类型{one:"one",two:"two"}) function 异步函数当从服务器返回json(此时的 json数据时string类型,使用需要转换称json结构类型,JSON.parse())

load get 传值

前端:

$(function(){

var odiv = $("#odiv");//div,将返回的数据显示在div中

var ousername = $("#username");//输入框

var otxt = $("#txt");// 文本输入框

var obtn = $("#obtn");//提交按钮

obtn.click(function () {

// $(this).load("server.php?username="+ousername.val()+"&txt="+otxt.val(),// 此时直接将需要传递的参数直接拼接在url上,data数据不需要设置

// function(responseText,status,xmlHttp){

// console.log(responseText);

console.log(typeof(JSON.parse(responseText)));

console.log(status);

console.log( typeof(xmlHttp.responseText));

// });

})

服务器:

$username = $_GET['username'];

$txt = $_GET['txt'];

$arr[] = $username;

$arr[] = $txt;

echo json_encode($arr);

load post传值

前端:

$(function(){

var odiv = $("#odiv");

var ousername = $("#username");

var otxt = $("#txt");

var obtn = $("#obtn");

obtn.click(function () {

$(this).load("server.php",{username:"lpf",txt:"11"},//此时将需要传递的参数以json格式作为data的参数传递

function(responseText,status,xmlHttp){

console.log(responseText);

// console.log(typeof(JSON.parse(responseText)));

// console.log(status);

// console.log( typeof(xmlHttp.responseText));

});

});

})

服务器端:

$username = $_POST['username'];

$txt = $_POST['txt'];

$arr[] = $username;

$arr[] = $txt;

echo json_encode($arr);

2. $.get(url,data,function(response,status,xmlhttp),dataType)

$.post(url,data,function(response,status,xmlhttp),dataType)

$.get和 $.post分别以get和post方式发送异步请求和load函数的差别在于最后独创的dataType的区别 dataType指的是服务器返回的数据,然后将其转换称dataType的数据类型

* dataType的指有

* "xml"、// typeof(response)=xml

* "html"// typeof(response)=html

* "text"// typeof(response)=text

* "script"// typeof(response)=script

* "json"// typeof(response)=json//最常用

* "jsonp"// typeof(response)=jsonp

3.ajax

$.ajax({

url: 'shoppingcart.php?a=addshopingcart',

type: 'post',

data: {'id': $("#id").val(), 'buynum': $("#buynum").val()},

dataType: 'html',// 返回值类型可以是text json html ,选择json时返回来的数据就是json格式的数据就不需要进行json转换了

success: function (data) {

if (a == "buy") {

location.href = "shoppingcart.php?a=buynow";

} else {

alert(data);

}

}

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值