首页 > 技术文章 > ajax 请求数据

oneone123 2019-12-13 09:22 原文

 

前端知识之ajax

ajax请求数据

ajax,谐音“阿贾克斯”,是英文AsynchronousJavascript And XML,中文翻译为异步ajax与xml数据传输技术.是一种网页的局部刷新技术,也可以叫网页无刷新技术.

ajax本质就是利用javascript提供的XMLHttpRequest对象代替浏览器到服务器里面指定的地址中传递参数和操作数据.这个过程可以在有用户不知情的情况下完成.

原生js的写法:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" name="city">
<button id="btn">获取</button>
<div class="info"></div>
<script>
// js中一般都会偷偷在不知道的情况下,使用ajax请求数据
var btn = document.querySelector("#btn");
btn.onclick = function(){
let city = document.querySelector("input[name=city]");

// 发送ajax请求数据
// get / post

// 1. 创建对象
let xhr = new XMLHttpRequest();
// 2. 创建一个http请求
xhr.open("get",`http://wthrcdn.etouch.cn/weather_mini?city=${city.value}`);
// console.log(xhr.readyState); //

// 3. 发送请求[如果是post,则需要在send里面传递需要发送给服务端地址的数据]
xhr.send();

// 4. 通过监控ajax的状态,判断ajax是否已经获取到了数据
xhr.onreadystatechange = function(){
// console.log(xhr.readyState);
// ajax的执行状态 1-4数值表示不同的进度
// 1. http请求已经创建完成
// 2. http请求已经发送
// 3. http请求由服务端接收了
// 4. 服务端已经处理完成本次http请求并响应成功
if(xhr.readyState === 4){
if(xhr.status === 200 ){
// 转换成json对象
let result = JSON.parse(xhr.responseText);
let data_list = result.data.forecast;
let info = document.querySelector(".info");
let st = `<table border="1" width="500">`;
st += `<tr>`;
st += `<td>日期</td><td>天气</td>`;
st += `</tr>`;

for( let data of data_list){
st += `<tr>`;
st += `<td>${data.date}</td><td>${data.type}</td>`;
st += `</tr>`;
}

st += `</table>`;
info.innerHTML = st;
}
}
}

}
</script>
</body>
</html>

jQuery中的ajax

$.ajax({
   type: "",         // http请求方法,get或者post
   url: "",          // 服务端地址
   data: "",         // 如果http请求方法是post,则可以在data编写要上传到服务端的数据
                     // 格式: 键=值&键=值&键=值....
   success: function(response){ // 当ajax执行成功了,则自动执行success对应的匿名函数
     alert( "Data Saved: " + response ); // 服务端返回的数据
   },
   fail: 
});

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-2.2.1.js"></script>
</head>
<body>
<input type="text" name="city">
<button id="btn">获取</button>
<div class="info"></div>
<script>
    $("#btn").on("click", function(){
       let $city = $("input[name=city]").val();
       // 发送ajax

       // $.ajax({
       //     type: "get",
       //     url: "http://wthrcdn.etouch.cn/weather_mini",
       //     data: `city=${$city}`,
       //     dataType: "json",
       //     success(response){
       //          console.log(response);
       //     },
       //     fail(error){
       //         console.log(error);
       //     }
       // });

       // jQuery也有 $.get() 和 $.post() 直接指定发送get或者post请求,两个方法使用一致
       $.get(`http://wthrcdn.etouch.cn/weather_mini`,{city: $city}, function(response){
           console.log(response);
       },"json");
    });
</script>
</body>
</html>

 

推荐阅读