.NET MVC第十章 vue axios解析web api接口

本文涉及的产品
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
全局流量管理 GTM,标准版 1个月
云解析 DNS,旗舰版 1个月
简介: .NET MVC第十章 vue axios解析web api接口

数据库

我用的是之前的数据库,用作测试,数据库的名称是【girl1804】


/*
Navicat SQL Server Data Transfer
Source Server         : mysqlserver
Source Server Version : 120000
Source Host           : .:1433
Source Database       : girl1804
Source Schema         : dbo
Target Server Type    : SQL Server
Target Server Version : 120000
File Encoding         : 65001
Date: 2022-10-05 20:24:26
*/
-- ----------------------------
-- Table structure for [dbo].[girlSix]
-- ----------------------------
DROP TABLE [dbo].[girlSix]
GO
CREATE TABLE [dbo].[girlSix] (
[id] varchar(32) NOT NULL DEFAULT (replace(newid(),'-','')) ,
[createDate] datetime NOT NULL DEFAULT (getdate()) ,
[nickName] varchar(30) NOT NULL ,
[introduce] nvarchar(200) NOT NULL 
)
GO
IF ((SELECT COUNT(*) from fn_listextendedproperty('MS_Description', 
'SCHEMA', N'dbo', 
'TABLE', N'girlSix', 
'COLUMN', N'nickName')) > 0) 
EXEC sp_updateextendedproperty @name = N'MS_Description', @value = N'名字'
, @level0type = 'SCHEMA', @level0name = N'dbo'
, @level1type = 'TABLE', @level1name = N'girlSix'
, @level2type = 'COLUMN', @level2name = N'nickName'
ELSE
EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'名字'
, @level0type = 'SCHEMA', @level0name = N'dbo'
, @level1type = 'TABLE', @level1name = N'girlSix'
, @level2type = 'COLUMN', @level2name = N'nickName'
GO
IF ((SELECT COUNT(*) from fn_listextendedproperty('MS_Description', 
'SCHEMA', N'dbo', 
'TABLE', N'girlSix', 
'COLUMN', N'introduce')) > 0) 
EXEC sp_updateextendedproperty @name = N'MS_Description', @value = N'介绍'
, @level0type = 'SCHEMA', @level0name = N'dbo'
, @level1type = 'TABLE', @level1name = N'girlSix'
, @level2type = 'COLUMN', @level2name = N'introduce'
ELSE
EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'介绍'
, @level0type = 'SCHEMA', @level0name = N'dbo'
, @level1type = 'TABLE', @level1name = N'girlSix'
, @level2type = 'COLUMN', @level2name = N'introduce'
GO
-- ----------------------------
-- Records of girlSix
-- ----------------------------
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'04e3d962adcb4a5b8fefaf8b46995e85', N'2020-05-27 09:05:52.000', N'董新颖', N'郭老师关门弟子之一。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'568fc305930347d3bec1ddd08c71ad29', N'2020-05-27 09:01:09.000', N'王笑涵', N'北方有佳人,绝世而独立。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'7eaa67475f0c4086a5e76ba1731196d2', N'2022-06-12 11:23:16.000', N'夏天', N'保持每天好心情。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'972ec358089042e0bf24fd9efca47bde', N'2020-05-27 08:59:49.000', N'牛龙珠', N'笑若桃花三月开,清风徐徐醉颜来。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'BDFFC6A36A53408281EB8CA242C0E7A3', N'2020-05-27 08:42:31.000', N'闫春娜', N'珠缨旋转星宿摇,花蔓抖擞龙蛇动。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'd1cdd67717e549caba16503787b55877', N'2021-02-17 15:27:41.357', N'小龙女', N'想过过过儿过过的日子');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'efb0ca854dac456b9d8c42d4c4b1bce0', N'2020-05-27 09:03:30.000', N'刘梓佳', N'明眸善睐,辅靥承权,瑰姿艳逸,怡静体闲,端的是好一个花王,富贵的牡丹。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'f839343b980e45caafaa9d2c9797294b', N'2020-05-27 09:04:53.000', N'魏慧娟', N'脉脉眼中波,盈盈花盛处。');
GO
-- ----------------------------
-- Indexes structure for table girlSix
-- ----------------------------
-- ----------------------------
-- Primary Key structure for table [dbo].[girlSix]
-- ----------------------------
ALTER TABLE [dbo].[girlSix] ADD PRIMARY KEY ([id])
GO

EF引入数据

image.png


等待完成后即可。


我们需要使用的是girl1804Entities

image.png



创建API控制器

image.png




接口编码

为了方便操作,我都写成HTTPGET请求了


获取信息


/// <summary>
/// 获取信息接口
/// </summary>
/// <returns></returns>
public object GetInfo()
{
    using (girl1804Entities db = new girl1804Entities())
    {
        return db.girlSix.ToList();
    }
}

添加信息


/// <summary>
/// 添加
/// </summary>
/// <param name="nickName"></param>
/// <param name="introduce"></param>
/// <returns></returns>
[HttpGet]
public bool AddInfo(string nickName, string introduce)
{
    using (girl1804Entities db = new girl1804Entities())
    {
        girlSix g = new girlSix();
        g.id = System.Guid.NewGuid().ToString("N");
        g.createDate = DateTime.Now;
        g.nickName = nickName;
        g.introduce = introduce;
        db.girlSix.Add(g);
        return db.SaveChanges() > 0;
    }
}


删除信息


/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public object DeleteById(string id)
{
    using (girl1804Entities db = new girl1804Entities())
    {
        girlSix g = db.girlSix.Where(o => o.id == id).SingleOrDefault();
        db.girlSix.Remove(g);
        return db.SaveChanges() > 0;
    }
}

单个查询


/// <summary>
/// 单个查询
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public object SelectById(string id)
{
    using (girl1804Entities db = new girl1804Entities())
    {
        return db.girlSix.Where(o => o.id == id).SingleOrDefault();
    }
}

修改方法

/// <summary>
/// 修改方法
/// </summary>
/// <param name="id"></param>
/// <param name="nickName"></param>
/// <param name="introduce"></param>
/// <returns></returns>
[HttpGet]
public bool UpdateById(string id, string nickName, string introduce)
{
    using (girl1804Entities db = new girl1804Entities())
    {
        girlSix girlSix = db.girlSix.Where(o => o.id == id).SingleOrDefault();
        if (girlSix == null)
        {
            return false;
        }
        girlSix.nickName = nickName;
        girlSix.introduce = introduce;
        return db.SaveChanges()>0;
    }
}


获取接口

image.png

接口


http://localhost:1246/api/gril1804/GetInfo
http://localhost:1246/api/gril1804/AddInfo?nickName={nickName}&introduce={introduce}
http://localhost:1246/api/gril1804/DeleteById/{id}
http://localhost:1246/api/gril1804/SelectById/{id}
http://localhost:1246/api/gril1804/UpdateById/{id}?nickName={nickName}&introduce={introduce}

根据接口解析操作即可。


网络js环境

bootstrap-css:【<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">】


JQuery:【<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>】


bootstrap:【<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>】


vue:【<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>】


axios:【<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>】


 

<!--用于bootstrap样式-->
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <!--用于bootstrap-->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!--用于样式-->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--用于基础操作-->
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <!--用于数据解析-->
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

完整示例:


<!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>Document</title>
    <!--用于bootstrap样式-->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div id="app">
        <div class="input-group">
            <span class="input-group-addon">昵称搜索:</span>
            <input type="text" v-model="selectKey" placeholder="请输入搜索昵称关键字" class="form-control" />
        </div>
        <table class="table table-bordered table-hover">
            <tr class="info">
                <th>编号</th>
                <th>创建时间</th>
                <th>昵称</th>
                <th>介绍</th>
                <th>操作</th>
            </tr>
            <!--遍历过滤后的集合-->
            <tr v-for="item in newlist">
                <td>{{item.id}}</td>
                <td>{{item.createDate}}</td>
                <td>{{item.nickName}}</td>
                <td>{{item.introduce}}</td>
                <td>
                    <button v-on:click="del(item.id)" class="btn btn-info">删除</button>
                    <button v-on:click="SetInfo(item)" class="btn btn-info">修改</button>
                </td>
            </tr>
        </table>
        <hr/>
        <div class="input-group">
            <span class="input-group-addon">编号:</span>
            <input type="text" v-model="id" disabled class="form-control" />
        </div>
        <div class="input-group">
            <span class="input-group-addon">创建时间:</span>
            <input type="text" v-model="createDate" disabled class="form-control" />
        </div>
        <div class="input-group">
            <span class="input-group-addon">昵称:</span>
            <input type="text" v-model="nickName" class="form-control" />
        </div>
        <div class="input-group">
            <span class="input-group-addon">简介:</span>
            <input type="text" v-model="introduce" class="form-control" />
        </div>
        <button v-on:click="Setting()" class="btn btn-info">完成修改</button>
        <button v-on:click="add()" class="btn btn-info">添加</button>
    </div>
    <!--用于bootstrap-->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!--用于样式-->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--用于基础操作-->
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <!--用于数据解析-->
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script>
        var urlBase = "http://localhost:1246/api/gril1804/";
        new Vue({
            el: "#app",
            data: {
                list: [],
                selectKey: "",
                id: "",
                createDate: "",
                nickName: "",
                introduce: ""
            },
            created() { //获取数据
                var _this = this;
                var url = urlBase + "GetInfo";
                axios.get(url).then(function(retult) {
                    console.log(retult.data);
                    _this.list = retult.data;
                })
            },
            computed: { //过滤数据
                newlist: function() {
                    var _this = this;
                    console.log(_this.list);
                    return _this.list.filter(function(o) {
                        return o.nickName.indexOf(_this.selectKey) != -1;
                    });
                }
            },
            methods: { //方法集合
                add: function() {
                    var url = urlBase + "addInfo?nickName=" + this.nickName + "&introduce=" + this.introduce;
                    axios.get(url).then(function(retult) {
                        if (retult.data) {
                            alert("添加成功");
                            location.reload();
                        }
                    })
                },
                del: function(o) {
                    if (confirm("是否删除此行")) {
                        var url = urlBase + "DeleteById?id=" + o;
                        axios.get(url).then(function(retult) {
                            alert("删除成功");
                            location.reload();
                        })
                    }
                },
                SetInfo: function(item) { //修改1
                    this.id = item.id;
                    this.createDate = item.createDate;
                    this.nickName = item.nickName;
                    this.introduce = item.introduce;
                },
                Setting: function() { //修改2
                    var url = urlBase + "UpdateById?id=" + this.id + "&nickName=" + this.nickName + "&introduce=" + this.introduce;
                    axios.get(url).then(function(retult) {
                        if (retult.data) {
                            alert("修改成功");
                            location.reload();
                        }
                    })
                }
            }
        })
    </script>
</body>
</html>


image.png


总结

axios使用方法相对更方便一些,加载数据也只需要在created中处理即可,如果有需要的话就搭建一个脚手架,如果不方便话使用那个都无所谓的,功能是肯定可以实现的,前提是接口一定要跨域啊,如果接口没有跨域是无法进行解析的。

相关文章
|
3天前
|
存储 供应链 监控
1688商品数据实战:API搜索接口开发与供应链分析应用
本文详细介绍了如何通过1688开放API实现商品数据的获取与应用,涵盖接入准备、签名流程、数据解析存储及商业化场景。开发者可完成智能选品、价格监控和供应商评级等功能,同时提供代码示例与问题解决方案,确保法律合规与数据安全。适合企业开发者快速构建供应链管理系统。
|
18天前
|
机器学习/深度学习 JSON 算法
淘宝拍立淘按图搜索API接口系列的应用与数据解析
淘宝拍立淘按图搜索API接口是阿里巴巴旗下淘宝平台提供的一项基于图像识别技术的创新服务。以下是对该接口系列的应用与数据解析的详细分析
|
1月前
|
JSON API 数据格式
阿里巴巴商品详情接口(阿里巴巴 API 系列)
在电商开发中,获取阿里巴巴商品详情信息对数据分析、竞品研究等至关重要。通过调用其商品详情接口,开发者可获取标题、价格、图片、描述等数据,满足多种业务需求。接口采用HTTPS协议,支持GET/POST请求,返回JSON格式数据。示例代码展示了如何使用Python的requests库进行接口请求,需传递商品ID和访问令牌。实际应用时,请依据官方文档调整参数并确保安全性。
64 10
|
17天前
|
存储 缓存 监控
如何高效爬取天猫商品数据?官方API与非官方接口全解析
本文介绍两种天猫商品数据爬取方案:官方API和非官方接口。官方API合法合规,适合企业长期使用,需申请企业资质;非官方接口适合快速验证需求,但需应对反爬机制。详细内容涵盖开发步骤、Python实现示例、反爬策略、数据解析与存储、注意事项及扩展应用场景。推荐工具链包括Playwright、aiohttp、lxml等。如需进一步帮助,请联系作者。
|
1月前
|
JSON API 数据格式
淘宝商品评论数据API接口详解及JSON示例返回
淘宝商品评论数据API接口是淘宝开放平台提供的一项服务,旨在帮助开发者通过编程方式获取淘宝商品的评论数据。这些数据包括评论内容、评论时间、评论者信息、评分等,对于电商分析、用户行为研究、竞品分析等领域都具有极高的价值。
|
13天前
|
关系型数据库 MySQL 数据库
基于Flink CDC 开发,支持Web-UI的实时KingBase 连接器,三大模式无缝切换,效率翻倍!
TIS 是一款基于Web-UI的开源大数据集成工具,通过与人大金仓Kingbase的深度整合,提供高效、灵活的实时数据集成方案。它支持增量数据监听和实时写入,兼容MySQL、PostgreSQL和Oracle模式,无需编写复杂脚本,操作简单直观,特别适合非专业开发人员使用。TIS率先实现了Kingbase CDC连接器的整合,成为业界首个开箱即用的Kingbase CDC数据同步解决方案,助力企业数字化转型。
62 5
基于Flink CDC 开发,支持Web-UI的实时KingBase 连接器,三大模式无缝切换,效率翻倍!
|
21天前
|
机器学习/深度学习 开发框架 API
Python 高级编程与实战:深入理解 Web 开发与 API 设计
在前几篇文章中,我们探讨了 Python 的基础语法、面向对象编程、函数式编程、元编程、性能优化、调试技巧以及数据科学和机器学习。本文将深入探讨 Python 在 Web 开发和 API 设计中的应用,并通过实战项目帮助你掌握这些技术。
|
5月前
|
XML JSON API
ServiceStack:不仅仅是一个高性能Web API和微服务框架,更是一站式解决方案——深入解析其多协议支持及简便开发流程,带您体验前所未有的.NET开发效率革命
【10月更文挑战第9天】ServiceStack 是一个高性能的 Web API 和微服务框架,支持 JSON、XML、CSV 等多种数据格式。它简化了 .NET 应用的开发流程,提供了直观的 RESTful 服务构建方式。ServiceStack 支持高并发请求和复杂业务逻辑,安装简单,通过 NuGet 包管理器即可快速集成。示例代码展示了如何创建一个返回当前日期的简单服务,包括定义请求和响应 DTO、实现服务逻辑、配置路由和宿主。ServiceStack 还支持 WebSocket、SignalR 等实时通信协议,具备自动验证、自动过滤器等丰富功能,适合快速搭建高性能、可扩展的服务端应用。
324 3
|
4月前
|
存储 前端开发 JavaScript
如何在项目中高效地进行 Web 组件化开发
高效地进行 Web 组件化开发需要从多个方面入手,通过明确目标、合理规划、规范开发、加强测试等一系列措施,实现组件的高效管理和利用,从而提高项目的整体开发效率和质量,为用户提供更好的体验。
131 63
|
4月前
|
开发框架 搜索推荐 数据可视化
Django框架适合开发哪种类型的Web应用程序?
Django 框架凭借其强大的功能、稳定性和可扩展性,几乎可以适应各种类型的 Web 应用程序开发需求。无论是简单的网站还是复杂的企业级系统,Django 都能提供可靠的支持,帮助开发者快速构建高质量的应用。同时,其活跃的社区和丰富的资源也为开发者在项目实施过程中提供了有力的保障。
187 62

热门文章

最新文章