jQuery ajax的使用

关于 jQuery 与 AJAX

几个从服务器上获取数据方法

1、$.ajax方法

(1、$.ajax({

       //请求的地址

       url:“https://showme.myhope365.com/api/shop/shopGoods/open/hot/listr”,

       //请求方式,

       Type:”get”.

       //请求参数

       Data:{

},

       //成功回调

       Success:function(res){},

//失败

       Error:function(res){

       Console.log(404)

}

2、$.get方法

$.get(“url地址”,{参数},function(res){console.log(res)})

3、$.post方法

$.post((“url地址”,{参数},function(res){console.log(res)})

//设置数据的传输格式

contentType: 是post里填,非必填项

// 发送之前输出beforeSend
beforeSend: function () {
console.log("123")
},

请求后输出complete
complete: function () {
console.log(“abc”)
}

4、load()方法

语法为:$(selector).load(URL,data,callback);

load()方法回调

例:

$(function () {
  $("#input").click(function () {
  //jquery中提供了一个1oad方法,功能:把请求回来的数据添加到指定的容器中
  $(".box").load("hello.txt", function (responseTxt, statusTxt, xhr) {
    console.log(responseTxt)//请求回来的内容
    console.log(statusTxt)//请求回来的状态 success error
    console.log(xhr)//ajax的实例对象
    })
  })
})

jsonp

jsonp是存储和交换文本信息的语法

例子:{ "name": "222", "age": 14}//别的属性和属性值除了数字外均必须加双引号,不能用单引号

  For in 和 foreach()两个循环遍历的方式

var   jsonobj={"name”:'李琳”,“age":18,'height':'180cm',"hobby":["学习”,”睡觉”,“吃饭”]};

console.1og(jsonobj.name)

console.log(jsonobj['age']);

console.1og(jsonobj.hobby)

for in循环遍历p

for(var key in jsonobj.hobby){

  //console.log(key)

document.write(jsonobj.hobby[key])}

foreach循环遍历

jsonobj.hobby.forEach(function (selector, index) {
  console.log(selector, index)
  alert(selector)
})

跨域

定义:协议、域名、端口号只要有一个不同,就是跨域

 

跨域解决方法:

jsonp(动态创建script标签,)

通过后台设置请求头

代理方式

posted on 2020-08-14 15:54  羡仙  阅读(159)  评论(0编辑  收藏  举报

导航