get和post
jQuery.get(url, [data], [callback], [type])
url:待载入页面的URL地址或接口远程API路径
data:发送url路径的 Key/value 参数。(若读取数据就不需要发送,可写可不写)
callback:载入成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
在本地服务器上,不牵扯跨域问题
json.json文件
[{
"name":"张三"
},{
"name":"李四"
},{
"name":"王麻子"
}]
//cros跨域这两种方法都可以
$.get("./data/json.json", function (res) {
console.log(res[1]);
}, "json")
$.post("./data/json.json", function (res) {
console.log(res[1]);
}, "json")
ajax
参数:method url data
dataType
success error
async
jsonpCallback
//这个代码cros跨域或者不跨域都可以使用
$.ajax({
method: "post",
url: "./data/json.txt",
data: "",
dataType:"json", //将其他文件格式转化为json格式
success: function (res) {
//成功返回值
console.log(res);
},
error: function (res) {
//错误返回值
},
async: true
})
jsonp跨域,需要写jsonpCallback,dataType的属性值为jsonp
jsonp跨域的请求方式不同,代码的写法也不同
get请求,getData直接写到URL接口后边,或者加上data属性,将getData写到data中
post请求,将getData写到data属性中
$.ajax({
method:"get",
url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1&cb=getData",
dataType:"jsonp",
jsonpCallback:"getData",
success:function(res){
console.log(res);
},
error:function(){
}
})
$.ajax({
method:"post",
url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?",
data:{wd:1,cb:"getData"},
dataType:"jsonp",
jsonpCallback:"getData",
success:function(res){
console.log(res);
},
error:function(){
}
})
区分同步和异步
默认为异步true 请求和后续代码同步进行
同步(先请求,再执行后续代码)会报错,主线程锁死(原生js不使用同步)
①异步:输出的是 null 1 data数据
②同步:输出的是 1 data数据 data数据
var data=null;
$.ajax({
method:"post",
url:"./data/json.json",
success:function(res){
console.log(1);
data=res;
console.log(data);
},
async:false
})
console.log(data);
getJSON
参数:url data callback 会自动转化为JSON格式
$.getJSON("./data/json.txt",function(res){
console.log(res);
})
getScript
参数 url callback
可以将其他的js文件导入到这个页面中
$.getScript("./js/Slider.js",function(res){
console.log(res);
//需要加转义字符
$("<script><\/script>").html(res).appendTo($("body"));
})