如何使用Ajax GET和POST并将表中的输出更改为dataType json?

如何解决如何使用Ajax GET和POST并将表中的输出更改为dataType json?

我想使用Highcharts制作与MySQL Workbench连接的图表。我已经连接到数据库并以表格形式显示数据。但是现在我想使用ajax get和post获取表中的数据以与图表(javascript文件)连接。现在,我在如何将数据类型更改为json时遇到问题,我不太了解如何使用Ajax,但我知道可以这样做。我使用了MVC asp.Net core 3.1。这是我的代码:

  1. 控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dashboard.Models;
using Microsoft.AspNetCore.Mvc;

namespace Dashboard.Controllers
{
    public class SystemappsController : Controller
    {
        public IActionResult Index()
        {
            Systemapps context = HttpContext.RequestServices.GetService(typeof(Dashboard.Models.Systemapps)) as Systemapps;
            return View(context.GetAllSystemappsModel());
        }
    }
}

  1. 模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace Dashboard.Models
{
    public class Systemapps
    {
        public string ConnectionString { get; set; }

        public Systemapps(string connectionString)
        {
            this.ConnectionString = connectionString;
        }

        private MySqlConnection GetConnection()
        {
            return new MySqlConnection(ConnectionString);
        }

        public List<SystemappsModel> GetAllSystemappsModel()
        {
            List<SystemappsModel> list = new List<SystemappsModel>();

            using (MySqlConnection conn = GetConnection())
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("select * from statistics",conn);

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add(new SystemappsModel()
                        {
                            time = reader["time"].ToString(),vehi_1 = Convert.ToInt32(reader["vehi_1"]),vehi_2 = Convert.ToInt32(reader["vehi_2"]),vehi_3 = Convert.ToInt32(reader["vehi_3"]),vehi_4 = Convert.ToInt32(reader["vehi_4"]),vehi_5 = Convert.ToInt32(reader["vehi_5"]),vehi_6 = Convert.ToInt32(reader["vehi_6"]),total_vehicle = Convert.ToInt32(reader["total_vehicle"])
                        });
                    }
                }
            }
            return list;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace Dashboard.Models
{
    public class SystemappsModel
    {
        //private Statistics context;

        public string time { get; set; }
        public int vehi_1 { get; set; }
        public int vehi_2 { get; set; }
        public int vehi_3 { get; set; }
        public int vehi_4 { get; set; }
        public int vehi_5 { get; set; }
        public int vehi_6 { get; set; }
        public int total_vehicle { get; set; }
    }


}

  1. HTML
@model IEnumerable<Dashboard.Models.SystemappsModel>

@{ 
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Data</h2>

<table class="table" id="staticsTable">
    <tr>
        <th>Time</th>
        <th>C1</th>
        <th>C2</th>
        <th>C3</th>
        <th>C4</th>
        <th>C5</th>
        <th>C6</th>
        <th>Total Vehicle</th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayTextFor(modelItem => item.time)</td>
            <td>@Html.DisplayTextFor(modelItem => item.vehi_1)</td>
            <td>@Html.DisplayTextFor(modelItem => item.vehi_2)</td>
            <td>@Html.DisplayTextFor(modelItem => item.vehi_3)</td>
            <td>@Html.DisplayTextFor(modelItem => item.vehi_4)</td>
            <td>@Html.DisplayTextFor(modelItem => item.vehi_5)</td>
            <td>@Html.DisplayTextFor(modelItem => item.vehi_6)</td>
            <td>@Html.DisplayTextFor(modelItem => item.total_vehicle)</td>
        </tr>
    } 

</table>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width-device-width,initial-scale=1.8" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/data.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/modules/export-data.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>


    <style>
        * {
            box-sizing: border-box;
        }

        /* Create two equal columns that floats next to each other */
        .column {
            float: left;
            width: 50%;
            padding: 10px;
            height: 500px; /* Should be removed. Only for demonstration */
        }

        /* Clear floats after the columns */
        .row:after {
            content: "";
            display: table;
            clear: both;
        }
        /* Style the buttons */
        .btn {
            border: none;
            outline: none;
            padding: 12px 16px;
            background-color: #f1f1f1;
            cursor: pointer;
        }

            .btn:hover {
                background-color: #ddd;
            }

            .btn.active {
                background-color: #666;
                color: white;
            }
    </style>
</head>
<body>

    <h2>List View or Grid View</h2>

    <p>Click on a button to choose list view or grid view.</p>

    <div id="btnContainer">
        <button class="btn" onclick="listView()"><i class="fa fa-bars"></i> List</button>
        <button class="btn active" onclick="gridView()"><i class="fa fa-th-large"></i> Grid</button>
    </div>
    <br>

    <div class="row">
        <div class="column" style="background-color: #ffffff;">
            <h2>Chart 1</h2>
            <div id="container_1"></div>
            <script src="~/js/Chart_1.js"></script>
        </div>
        <div class="column" style="background-color:#ffffff;">
            <h2>Chart 2</h2>
            <div id="container_2"></div>
            <script src="~/js/Chart_2.js"></script>
        </div>
    </div>

    <div class="row">
        <div class="column" style="background-color:#ffffff;">
            <h2>Chart 3</h2>
            <div id="container_3"></div>
            <script src="~/js/Chart_3.js"></script>
        </div>
        <div class="column" style="background-color:#ffffff;">
            <h2>Chart 4</h2>
            <div id="container_4"></div>
            <script src="~/js/Chart_4.js"></script>
        </div>
    </div>

    <script>
        // Get the elements with class="column"
        var elements = document.getElementsByClassName("column");

        // Declare a loop variable
        var i;

        // List View
        function listView() {
            for (i = 0; i < elements.length; i++) {
                elements[i].style.width = "100%";
            }
        }

        // Grid View
        function gridView() {
            for (i = 0; i < elements.length; i++) {
                elements[i].style.width = "50%";
            }
        }

        /* Optional: Add active class to the current button (highlight it) */
        var container = document.getElementById("btnContainer");
        var btns = container.getElementsByClassName("btn");
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener("click",function () {
                var current = document.getElementsByClassName("active");
                current[0].className = current[0].className.replace(" active","");
                this.className += " active";
            });
        }
    </script>

</body>
</html>
  1. JavaScript
$(document).ready(function () {




    /*
     Load the data from the CSV file. This is the contents of the file:
     
        Apples,Pears,Oranges,Bananas,Plums
        John,8,4,6,5
        Jane,3,2,3
        Joe,86,76,79,77
        Janet,16,13,15
        
     */
    Highcharts.chart('container_1',{
        chart: {
            type: 'line',zoomType: 'x',data: []
        },title: {
            text: 'Vehicle Count with Classification'
        },subtitle: {
            text: '2018-8058 Puchong Survey: Direction 1: From Bandar Puteri Puchong/Cyberjaya to Bandar Puchong Jaya/ Taman Kinrara'
        },yAxis: {
            title: {
                text: 'Total Count'
            }
        }
    });




});


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-