ajax() 方法用于执行 AJAX(异步 HTTP)请求。
所有的 jQuery AJAX 方法都使用 ajax() 方法。该方法通常用于其他方法不能完成的请求。
jQuery ajax()方法 语法:
$.ajax({name:value, name:value, ... })
部分代码演示:
<script>// 1. load(): 请求数据, Html代码片断$("button:first-of-type").click(function(){$(this).after("<div>").next().load("ym.html");});// 2. $.get(): 幂操作$("button:nth-of-type(2)").click(function(ev){$.get("users.php",{id:2},function (data){console.log(data);$(ev.target).after("<div>").next().html(data);});});// 3. $.post():$("button:nth-of-type(3)").click(function(ev){$.post("users.php",{id:1},function(data){console.log(data)$(ev.target).after("<div>").next().html(data);})})$("button:nth-of-type(4)").click(function (ev) {$.getJSON("users.php?id=3", function (data) {// 从服务器返回josn会自动解析为JS对象,JSON.parse()console.log(data);data = `${data.id}: ${data.name}, 年龄: ${data.age}`;$(ev.target).after("<div>").next().html(data);});});$("button:nth-of-type(5)").click(function (ev) {$.ajax({// 请求类型type: "GET",// 请求URLurl: "users.php",// 发送的数据data: { id: 1 },// 希望服务器返回的数据类型dataType: "html",// 成功的回调处理方法success(data) {$(ev.target).after("<div>").next().html(data);},});});// 6. $.ajax()-jsonp: 跨域请求数据1$("button:nth-of-type(6)").click(function (ev) {$.ajax({type: "GET",// jsonp=?, ?是回调方法的占位符,请求发送时用jsonpCallback替换url: "http://php.io/test.php?id=2&jsonp=?",dataType: "jsonp",jsonpCallback: "handle",});});function handle(data) {console.log(data);data = `Name: ${data.name}, Email: ${data.email}`;$("button:nth-of-type(6)").after("<div>").next().html(data);}// 7. $.ajax()-jsonp: 跨域请求数据2$("button:last-of-type").click(function (ev) {$.ajax({type: "GET",// jsonp=?, ?是回调方法的占位符,请求发送时用jsonpCallback替换url: "http://php.io/test.php?id=3&jsonp=?",dataType: "jsonp",success(data) {console.log(data);data = `Name: ${data.name}, Email: ${data.email}`;$("button:last-of-type").after("<div>").next().html(data);},});});</script>
效果展示
//设置请求类型 type:”get/post”,
//设置请求地址 url: “url地址” ,
//发送数据 数据保存在date里面 date值是查询条件 date:” {id:1}” ,
//设置服务器希望返回的数据类型 datetype:” html/json/…”,
//请求成功后的回调函数 succes( 设置函数的参数 ){ 设置函数 }
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号