Express运用AJAX及实现JSONP

news/2024/7/24 2:25:40 标签: node.js, express, jsonp

一、get请求:

index.html

<html>
<head>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<input type="button" value="Ajax" id="get-data"/>

<script type="text/javascript">
$(document).ready(function () {
    $('#get-data').click(function (e) {
        $.ajax({
            url:'/get_data',
            type:'get',
            data:{},
            success:function (data) {
				console.log(data);
            },
            error:function (err) {

            }
        });
    });
});
</script>
</body>
</html>

test.js

const express = require("express");
const app = express();

//定义一个存放静态资源的目录
app.use('/src', express.static("src"));

app.get("/index.html", function(req, res, next){
	res.sendFile( __dirname + "/" + "index.html" );
})

app.get("/get_data", function(req, res, next){
    var obj = {
            title:'耶鲁留学生的2000张自拍照',
            src:'腾讯新闻',
            content:'推动新一代人工智能健康发展 更好造福世界各国人民'
        }
   res.json(obj);
})

const server = app.listen(8080, function(){
	console.log("启动成功!");
})

二、post请求:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>

<body>
<form action="/get_data" method="POST">
    First Name: <input type="text" id="first-name">  <br>

    Last Name: <input type="text" id="last-name">
    <input type="button" value="提交" id="get-data"/>
</form>

<script>
$(function(){
    $("#get-data").click(function(){
        $.ajax({
            type: "POST",
            url: '/get_data',
            data: {'firstName': $("#first-name").val(), 'lastName': $("#last-name").val()},
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (data) {
                console.log(data);
            }
        })
    })
})
</script>
</body>
</html>

index.js:

let express = require("express");
let app = express();
let bodyParser = require("body-parser");

let urlencodedParser = bodyParser.urlencoded({extended: false});

app.get("/index", function(req, res, next){
    res.sendFile(__dirname + "/views/" + "index.html")
})

app.post("/get_data", urlencodedParser, function(req, res, next){
    let response = {
        first_name: req.body.firstName,
        last_name: req.body.lastName
    }

    res.type("application/json");
    res.jsonp(response);
});

app.listen(8080, function(){
    console.log("开始请求");
})

三、JSONP(只有get方法支持):

8080端口:

let express = require("express");
let app = express();

app.use("/public", express.static("public"));

app.get("/index", function(req, res, next){
    res.sendFile(__dirname + "/" + "views/index.html");
});

app.get("/get_data", function(req, res, next){
    let response = {
        "title": "耶鲁留学生的2000张自拍照",
        "content": "耶鲁留学生的2000张自拍照,耶鲁留学生的2000张自拍照,耶鲁留学生的2000张自拍照,耶鲁留学生的2000张自拍照,耶鲁留学生的2000张自拍照"
    };
    res.type('application/json');
    res.jsonp(response);
});

app.listen(8080, function(){
    console.log("开始执行请求");
});

8000端口:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>

<input type="button" value="获取数据" id="get-data"/>

<script>
    $(function(){
        $("#get-data").click(function(){
            $.ajax({
                type: "GET",
                url: 'http://127.0.0.1:8080/get_data',
                data: {},
                dataType: "jsonp",
                success: function(data){
                    console.log(data);
                },
                error: function(data){

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

 


http://www.niftyadmin.cn/n/886627.html

相关文章

java MDC_Java日志Log4j或者Logback的NDC和MDC功能

NDC和MDC的区别Java中使用的日志的实现框架有很多种&#xff0c;常用的log4j和logback以及java.util.logging&#xff0c;而log4j是apache实现的一个开源日志组件(Wrapped implementations)&#xff0c;logback是slf4j的原生实现(Native implementations)。需要说明的slf4j是Ja…

vue路由4:手动访问和传参

index.html: <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Title</title> </head> <body> <div id"app"><div><router-link to"/">首页&…

Vue中使用qrcodejs2插件实现二维码生成及二维码图片下载

首先安装qrcodejs2插件&#xff1a; cnpm install qrcodejs2 --save 引入页面&#xff1a; import QRCode from "qrcodejs2"; 页面标签&#xff1a; <div id"qrcode" ref"qrcode"></div> 可以使用id 或者ref&#xff0c;建议使…

java web编程技术解题与实验指导_Java Web编程技术(第3版)题解与实验指导

第1章 Java Web技术概述 11.1 知识点总结 11.2 实训任务 11.3 思考与练习答案 9第2章 Servlet核心技术 112.1 知识点总结 112.2 实训任务 122.3 思考与练习答案 17第3章 JSP技术基础 213.1 知识点总结 213.2 实训任务 223.3 思考与练习答案 27第4章 会话与文件管理 324.1 知识点…

My97 DatePicker日期控件中设置好时间后立刻执行相关函数

My97 DatePicker日期控件官网&#xff1a;My97日期控件 演示 & 文档 My97 DatePicker Demo & Doc 方法&#xff1a; 在input 标签中加入onfocus &#xff0c;就可以了。 wdatePicker()可以自定义事件函数。 <input type"text" id"time" nam…

Vue性能优化方法与技巧大全

Vue 框架通过数据双向绑定和虚拟 DOM 技术&#xff0c;帮我们处理了前端开发中最脏最累的 DOM 操作部分&#xff0c; 我们不再需要去考虑如何操作 DOM 以及如何最高效地操作 DOM&#xff1b;但 Vue 项目中仍然存在项目首屏优化、Webpack 编译配置优化等问题&#xff0c;所以我们…

java返回数据给前端_JAVA后台转换成树结构数据返回给前端的实现方法

我们会经常用到树形&#xff0c;那么树形结构的数据是在前端做还是在后台做呢&#xff1f;我自己用过前端的ztree,selectTree等这些属于前端的组件&#xff0c;后台只需要把一个表的所有数据返回给前段就可以&#xff0c;前端可以通过id,pid来把层级结构划分&#xff0c;要是我…

vue+element项目中对echarts图表随着浏览器窗口resize的处理

知识点&#xff1a; mixins、ref、$refs、element响应式布局 准备工作&#xff1a; 1、项目中安装echarts&#xff1a; cnpm i echarts -S 2、在main.js中引入echarts&#xff1a; import echarts from echarts // 在原型链中注册&#xff0c;然后在需要的页面调用&#…