【问题标题】:querying javascript through html通过html查询javascript
【发布时间】:2016-05-31 13:57:43
【问题描述】:

我有一个 .js 文件和一个 .html 文件,我希望 html 文档从 .js 文件中获取数据并对其进行操作以生成饼图。我应该如何处理它?

目前,我在 .js 文件中有一个函数。我想在 html 命令中调用它。

编辑: 我在 html 中准备好了图表,并在 js 中查询了数据库。我只剩下链接它们了。我想根据 mssql 数据库中的数据值显示饼图

这是我的 html 文件 index12.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
  <script> </script>

<style>

    rect{                                              
        stroke-width: 2;                                          
        }  
    .legend{                                                
         stroke:black;
         opacity:1; 
         font-size: 12px; 
         }

    text{                                               
        font-family: sans-serif;
        font-size: 10px;
        fill:black;
        }

 </style>
 </head>
 <body>
 <p>hi how  ru</p>
<div id="chart"></div>
  <button type="button">Change Content</button>
 <script src="ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js></script>

      <script src="d3/d3.js"></script>
      <select id ="slctmodel"></select>
      <script>
      var dataset;
            $(document).ready(function () {
            $.getJSON("app.js", success = function (data) {
              dataset = data;
                                 });

          setTimeout(function () {

              /* dataset = [
                         { "module": "A", "errors": 50 },
                         { "module": "B", "errors": 120 },
                         { "module": "C", "errors": 10 },
                         { "module": "D", "errors": 200 },
                         { "module": "E", "errors": 27 },
                         { "module": "F", "errors": 25 },
                         { "module": "G", "errors": 40 }
               ];*/
              console.log(dataset);
              var width = 1500;                                  
              var height = 1500;
              var radius = 150;

              var legendRectSize = 16;                           
              var legendSpacing = 4;                              
              console.log("hi1");
              var color = d3.scale.ordinal()                         
                    .domain(["A", "B", "C", "D", "E", "F", "G", ])
                    .range(["#FFEBAA", "#EEAB79", "#955C52", "#BE4C60",
                         "#B42E61", "#851362", "#5E0063"]);
              var svg = d3.select('#chart')                      
                    .append('svg')
                    .attr('width', width)
                    .attr('height', height)
                    .append('g')
                    .attr('transform', 'translate(' + 850 + ',' + 250+')');

              d3.select('#chart svg')                                    
                    .append("text")
                    .attr("x", 850)
                    .attr("y", 30)
                    .attr("text-anchor", "middle")
                    .text("PROBABILITY OF FAILURE IN MODULES");      

              var arc = d3.svg.arc()                                     
                    .innerRadius(30)
                    .outerRadius(radius);

              var arcOver = d3.svg.arc()                         
                    .innerRadius(20)
                    .outerRadius(radius + 30);
              console.log("hi2");
              var pie = d3.layout.pie()                      
                    .value(function (d) { return d.errors; })
                    .sort(null);                             
              var path = svg.selectAll('path')               
                    .data(pie(dataset))
                    .enter()
                    .append('path')
                    .attr('d', arc)
                    .attr('fill', function (d, i) {
                        return color(d.data.module);
                    })
                    .attr("opacity", 1)
                    .attr("stroke", "black")
                    .attr("stroke-width", 2)
                    .on("mouseenter", function (d) {             
                        d3.select(this)
                      .attr("stroke", "black")
                      .transition()
                      .duration(1000)
                      .attr("d", arcOver)
                      .attr("stroke-width", 4)
                      .attr("opacity", 1)
                    })
                    .on("mouseleave", function (d) {         
                        d3.select(this).transition()
                       .attr("d", arc)
                       .attr("stroke", "black")
                       .attr("stroke-width", 2)
                       .attr("opacity", 1);
                    })
              console.log("hi3");
              svg.selectAll('text')
                  .data(pie(dataset))
                  .enter()
                  .append('text')
                  .attr("transform", function (d) {      
                      return "translate(" + arc.centroid(d) + ")";
                  })
                  .attr("text-anchor", "middle")
                  .text(function (d) {
                      return d.value;
                  })
                  .style("pointer-events", "none");



              var legend = svg.selectAll('.legend')                 
                    .data(color.domain())
                    .enter()
                    .append('g')
                    .attr('class', 'legend')
                    .attr('transform', function (d, i) {
                        var height = legendRectSize + legendSpacing;
                        var offset = height * color.domain().length / 2;

                        var vert = i * height - offset;
                        return 'translate(' + 250 + ',' + vert + ')';
                    });
              console.log("hi4");
              legend.append('rect')                                     
                    .attr('width', legendRectSize)
                    .attr('height', legendRectSize)
                    .style('fill', color)
                    .style('stroke', color);

              legend.append('text')                                     
                    .attr('x', legendRectSize + legendSpacing)
                    .attr('y', legendRectSize - legendSpacing)
                    .text(function (d) { return d; });

              console.log("hi5");
          }
      , 500);

 });

</script>
</body>
</html> 

我的 APP.JS 文件是

var http = require('http');                         //connect with http
var sql = require('mssql');                         //connect with sql
var express = require('express');                   //connect with express
var path = require('path');
var app = express();
var jQ = require('jquery');
env: {
browser: true
 }

var Connection = sql.Connection;
var Request = sql.Request;

var a; var recordSet;

var config = {
server: '10.2.13.211',                          //my IP address - obtained        
//server: '.',
database: 'trialdb',                            //my table is within this      
user: 'sa',                                     //windows authentication           
password: 'admin123#',
port: 1433                                      //deafault port number
};

function send404Response(response) {
response.writeHead(404, { "Context-Type": "text/plain" });                                   
response.write("Error 404:Page not found");
response.end();                                                                
}

function loadEmployees() {                                                          

var dbConn = new sql.Connection(config);

dbConn.connect().then(function () {                                             

    var request = new sql.Request(dbConn);

    request.query("select * from list").then(function (recordSet) {         
        //  console.log(recordSet);
        a = recordSet[1].errors;
        return recordSet;
        dbConn.close();                                                      //close connection
    }).catch(function (err) {

        console.log(err);
        dbConn.close();
    });
}).catch(function (err) {

    console.log(err);
});


}


app.use(express.static('D:/d3 project/project_part1/project_part1/'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '../../index12.html'));
//res.send(recordSet);
});


app.get('/abt', function (req, res) {
res.sendFile(path.join(__dirname, '../../startpage.html'));
});

function onRequest(request, response) {
if (request.method == 'GET' && request.url == '/') {
    console.log("user made a request" + request.url);
    response.writeHead(200, { "Context-Type": "text/plain" });
    loadEmployees();
    setTimeout(function () {
        // response.write("here is some data");
        response.write("hiya" + a);
        response.end();
    }
        , 200);
}
else {
    send404Response(response); console.log('error 404');
}
}

http.createServer(onRequest).listen(8888);                                         
console.log('server will run on requset to port 8888');
var server = app.listen(8081);

我在 index12.html 文件的 jquery 部分中的“数据”变量有一个未定义的值。它应该具有 app.js 文件中的“记录集”变量的值

我该如何进行呢?

如何在 index12.html 中调用 app.js 的函数 loadEmployees(),以便可以存储函数 loadEmployees() 返回的值,即 index12.html 的“数据”变量中的“记录集”

【问题讨论】:

  • 形成你的问题,我知道你只是想在 html 中加入那个 JS,只需写一个 &lt;script&gt; 标签并访问它有什么问题。如果问题在于绘制图表那么你可以参考@afuc的回答
  • 如果在我的
  • 你能分享代码并告诉我你想要实现什么吗?
  • 您需要 jquery/javascript 来修改 html dom 元素。共享代码,以便清楚您要实现的目标。您需要将响应数据提供给图表。

标签: jquery html node.js


【解决方案1】:

使用 chart.js 库在 html 上创建图表。

参考http://www.chartjs.org/

【讨论】:

  • 我已经在html上准备好了图表,我已经在js中查询了mssql数据库。我想链接它们
  • 你是如何制作图表的?如果只想访问html中的js变量,参考:stackoverflow.com/questions/14845710/…
  • 我已经有一个
  • 为 jQuery 添加 &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"&gt;&lt;/script&gt;
  • 是的,我这样做了,现在,我需要调用一个函数而不是整个文件?这可能>
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2015-02-10
  • 2023-04-10
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
相关资源
最近更新 更多