有三种方法:
(1)node.load(url),
将服务器响应插入当前jQuery对象匹配的dom元素
之内。一般用于从服务器获取静态的数据(html)$(function(){ $('a:eq(1)').toggle(function(){ $(this).next().load('getPrice'); $(this).html('显示经济舱价格'); },function(){ $(this).html('显示全部价格'); $(this).next().empty(); }); });
说明:
toggle() 方法切换元素的可见状态。如果被选元素可见,则隐藏这些元素,如果被选元素隐藏,则显示这些元素。
(2)$.get(url,[data],[callback],[type]):
其中,callback格式 function(data,statusText)
$.post()格式同上。
$(function(){
$.get('quoto',null,function(data,statusText){
$('#d1').html('name:' + data.stockName+' ' + 'price:' + data.stockPrice);
},'json');
});
(3)$.ajax(options):options是一个形如{key1:value1,key2,value2...}的js对象,用于指定发送请求的选项。
选项参数如下:
url(string):请求地址
type(string):GET/POST
data(object/string):发送到服务器的数据
dataType(string) :预期服务器返回的数据类型,一般有:
xml:返回xml文档
html:返回html文本
script:javascript脚本
json: 返回的是符合json语法
格式的文本,jQuery会将
该文本转化为js对象。
text:返回普通文本
success(function):请求成功后调用的回调函数,有两个参数:
function(data,textStatus),其中,
data是服务器返回的数据,可以是html,text,jsonObj,xmlDoc
textStatus 描述状态的字符串。
error(function):请求失败时调用的函数,有三个参数
function(XmlHttpRequest,textStatus,errorThrown)
$(function(){ $('select').change(function(){ $('#d1').remove(); $.ajax( { url:"carInfo", type:'post', data:$('select').serialize(), dataType:'html', success:function(data,status){ $('select').after("<div id='d1'></div>"); $('#d1').html(data); }, error:function(xhr,textStatus,errorThrown){ alert(textStatus); //alert(xhr.status); } }); }); });