1.原生ajax

    1. var url = "http://192.168.4.18:8000/"
    2. var xhr = new XMLHttpRequest();
    3. xhr.open("get", url, true);
    4. xhr.send();
    5. xhr.onreadystatechange = function () {
    6. if (xhr.readyState == 4 && xhr.status == 200) {
    7. var result = JSON.parse(xhr.responseText);
    8. console.log(result)
    9. }
    10. }

    2.回调函数去封装ajax

    1. // 需要记住传参的顺序
    2. function ajax(url,method="get",success) {
    3. var xhr = new XMLHttpRequest();
    4. xhr.open(method, url, true);
    5. xhr.send();
    6. xhr.onreadystatechange = function () {
    7. if (xhr.readyState == 4 && xhr.status == 200) {
    8. var result = JSON.parse(xhr.responseText);
    9. success(result)
    10. }
    11. }
    12. }
    1. function ajax({
    2. url,
    3. method="get",
    4. success
    5. }) {
    6. var xhr = new XMLHttpRequest();
    7. xhr.open(method, url, true);
    8. xhr.send();
    9. xhr.onreadystatechange = function () {
    10. if (xhr.readyState == 4 && xhr.status == 200) {
    11. var result = JSON.parse(xhr.responseText);
    12. success(result)
    13. }
    14. }
    15. }

    3. jquery-ajax

    1. $.ajax({
    2. url:"http://192.168.4.18:8000/",
    3. type:"get",
    4. dataType:"json",
    5. success:res=>{
    6. console.log(res)
    7. }
    8. })

    4.callback封装jquery-ajax

    1. function http({url,type="get",success}){
    2. $.ajax({
    3. url,
    4. type,
    5. dataType:"json",
    6. success:res=>{
    7. success(rs)
    8. }
    9. })
    10. }