官网网站建设企业seo精华网站
原生jsonp跨域请求
输入框:输入后,鼠标移开向服务端发送请求,返回用户不存在(直接返回不存在,不做判断)
JS
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>案例</title>
</head>
<body>用户名: <input type="text" id="username"><p></p><script>//获取 input 元素const input = document.querySelector('input');const p = document.querySelector('p');//声明 handle 函数function handle(data){input.style.border = "solid 1px #f00";//修改 p 标签的提示文本p.innerHTML = data.msg;}//绑定事件input.onblur = function(){//获取用户的输入值let username = this.value;//向服务器端发送请求 检测用户名是否存在//1. 创建 script 标签const script = document.createElement('script');//2. 设置标签的 src 属性script.src = 'http://127.0.0.1:8000/check-username';//3. 将 script 插入到文档中document.body.appendChild(script);}</script>
</body>
</html>
服务
//用户名检测是否存在
app.all('/check-username',(request, response) => {// response.send('console.log("hello jsonp")');const data = {exist: 1,msg: '用户名已经存在'};//将数据转化为字符串let str = JSON.stringify(data);//返回结果response.end(`handle(${str})`);
});