ajax 第十九节 AJAX-jQuery发送jsonp请求
============index.html ============
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery-jsonp</title>
<style>
#result {
width: 300px;
height: 100px;
border: solid 1px red;
}
</style>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
<button>点我发送 Jsonp 请求</button>
<div id="result"></div>
<script>
$('button').eq(0).click(function () {
$.getJSON('http://127.0.0.1:8000/jquery-jsonp-server?callback=?', function (data) {
//此外为返引号$('#result').html(`xxxxx`)
$('#result').html(`
名称:${data.name}<br>
校区:${data.city}
`)
})
})
</script>
</body>
</html>
=================server.js=====================
const { request, response } = require('express');
const express = require('express');
const app = express();
app.all('/jquery-jsonp-server', (request, response) => {
const data = { name: 'DX33', city: ['北京', '上海', '天津'], age: '18' };
let str = JSON.stringify(data);
let cb = request.query.callback;
//模板字符串,此处使用的是返引号
response.send(`${cb}(${str})`);
})
app.listen(8000, () => {
console.log('服务已经启动,8000端口监听中.......');
})