快速上手
$.ajax({ url:'data.json', type:'get', data:{id:1,type:'onsale'}, //用于提交到服务端的参数 dataType:'json', //用于设置响应体的类型 beforeSend:function(xhr){ //请求发送之前 console.log(xhr) }, success:function(res){ //状态码200 console.log(res) //res会自动根据服务端响应的Content-Type自动转换为对象 }, error:function(xhr){ //状态码不是200 console.log(xhr) }, complete:function(xhr){ //不管是不是200,都会执行 cosole.log(xhr) } })
相关属性解释
data
$.get(url,data,function(res){
})
从jQuery 1.4开始,如果JSON文件包含一个语法错误,该请求通常会静静的失败。因此应该避免频繁手工编辑JSON数据。JSON语法规则比JavaScript对象字面量表示法更加严格。例如,所有在JSON中的字符串,无论是属性或值,必须用双引号括起来。
//为了防止服务端不加Content-Type $.getJSON(url,data,function(res){
})
$.getScript(url) .done(function(script, textStatus) { }) //从jQuery 1.5开始,以用.fail()来处理错误: .fail(function(jqxhr, settings, exception) { });
$.post(url,data,function(res){ })
默认使用 GET 方式 - 传递附加参数时自动转换为 POST 方式。jQuery 1.2 中,可以指定选择符,来筛选载入的 HTML 文档,DOM 中将仅插入筛选出的 HTML 代码。语法形如 "url #some > selector"。请查看示例。
//load(url,[data],[callback]) $("#links").load("/Main_Page #p-Getting-Started li");