前后端交互Ajax加强
warning:
这篇文章距离上次修改已过191天,其中的内容可能已经有所变动。
在前后端交互的三种方式中,Ajax是一种常用的方法,它可以使得页面的局部刷新成为可能。下面是一个使用Ajax进行前后端交互的例子。
前端代码:
<!DOCTYPE html>
<html>
<head>
<title>Ajax Example</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<h2>Ajax 加强</h2>
<button id="ajax_btn">点击发送请求</button>
<div id="result"></div>
<script>
$(document).ready(function(){
$("#ajax_btn").click(function(){
$.ajax({
url: "https://api.myjson.com/bins/9inum", // 这是一个JSON数据接口
type: "get", // 请求方法
dataType: "json", // 返回的数据类型
success: function(response){ // 请求成功后的回调函数
var html = '<ul>';
$.each(response, function(key, value) {
html += '<li>Key: ' + key + ', Value: ' + value + '</li>';
});
html += '</ul>';
$('#result').html(html); // 将返回的数据显示在页面上
}
});
});
});
</script>
</body>
</html>
后端代码(这里以JSON数据接口为例):
{
"name": "John",
"age": 30,
"city": "New York"
}
这个例子中,前端使用jQuery封装的$.ajax()
函数向后端发送请求,后端返回一个JSON对象,前端接收到数据后,遍历这个对象,并将数据以列表的形式显示在页面上的<div id="result"></div>
元素中。
评论已关闭