ajax--后台springboot向html传参

22 篇文章 0 订阅
8 篇文章 0 订阅

前几天弄js向后台传参网上有很多教程,但是反过来就都是一些繁琐的方法,我参考php/asp向前端传参的方式改了一下
思路:javascript通过一个函数发送xmlhttprequest请求给后台,用responsetext接收后台return 的数据

ccc.html

注意:这里面的ajax代码有一个参数str,本例未使用(随便给了个字符),这个参数可以用来帮助数据库的模糊查询等等功能
点击按钮即可显示后台传的参数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function showUser(str) {
            if (str=="") {
                document.getElementById("txtHint").innerHTML="";
                return;
            }
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function() {
                if (this.readyState==4 && this.status==200) {
                    document.getElementById("txtHint").innerHTML=this.responseText;
                }
            }
            xmlhttp.open("GET","/ajaxtest1?q="+str,true);
            xmlhttp.send();
        }
    </script>

</head>
<body>
<div id="txtHint"><b>客户信息将在此处列出。</b></div>
<button onclick="showUser('q')">按钮</button>
</body>
</html>
ajaxtest1.java

这是一个springboot的控制器

package aaa.j2ee2.controller;


import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ajaxtest1 {



    @RequestMapping(value = "/ajaxtest1")
    @ResponseBody

    public String up(@RequestParam("q") String name){



        return "hello ajax";







    }
}

在这里插入图片描述

返回数据库的数据

注意:需要在application.yml配置数据库

package aaa.j2ee2.controller;


import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;


@Controller
public class ajaxtest1 {

    @Autowired
    JdbcTemplate jdbcTemplate;


    @RequestMapping(value = "/ajaxtest1")
    @ResponseBody

    public List up(@RequestParam("q") String name) {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from j2ee2");
        int n = 0;
     /*   while (n < list.size()) {
            String a = list.get(n).toString();
            n += 1;
            return a;
        }
*/
        return list;



    }


后台将查到的list格式数据转化为json,以便js接收(echart实例)

实例:springboot后台查询温度,前端用echart显示
ajaxtest1.java,需要配置application.yml数据库参数
注意
var data1 = JSON.parse(this.responseText),将后台发来的数据转换为json格式,
data1[i].temperature;data[i 取json第i个键值对,.temperature获取这行数据的temperature数值
但如果想对这种数据进行运算,需要强制转换类型为Number
sum=sum+Number(data1[i].temperature);

package aaa.j2ee2.controller;


import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;

@Controller
public class ajaxtest1 {

    @Autowired
    JdbcTemplate jdbcTemplate;


    @RequestMapping(value = "/ajaxtest1")
    @ResponseBody

    public String up(@RequestParam("q") String name) {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select temperature from j2ee2 order by id desc limit 10");
        List list1 = jdbcTemplate.queryForList("select * from j2ee2");
        String listJson = JSON.toJSONString(list);
        return listJson;


     /*   while (n < list.size()) {
            String a = list.get(n).toString();
            n += 1;
            return a;
        }
*/



    }


echar.html(拼错了)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="js/echarts.min.js"></script>
	</head>
	<body>
		<div id="main" style="width: 600px;height:400px;"></div>
			
		</div>
		<script>
		
	
		var chartDom = document.getElementById('main');
		var myChart = echarts.init(chartDom);
		var option;

		option = {
		    xAxis: {
		        type: 'category',
		        data: ['1', '2', '3', '4', '5', '6', '7','8','9','10']
		    },
		    yAxis: {
		        type: 'value'
		    },
		    series: [{
		        data: [150, 230, 224, 218, 135, 147, 260,100,100,100],
		        type: 'line'
		    }]
		};
		
		option && myChart.setOption(option);
var str='abc';
		timeTicket = setInterval(function(str) {
			if (str=="") {
				document.getElementById("txtHint").innerHTML="";
				return;
			}
			if (window.XMLHttpRequest) {
				// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp=new XMLHttpRequest();
			} else { // code for IE6, IE5
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			xmlhttp.onreadystatechange=function() {
				if (this.readyState==4 && this.status==200) {
				//	option.series[0].data[0]=this.responseText
					var data1 = JSON.parse(this.responseText);
					for(var i=0;i<10;i++)
					{option.series[0].data[i]=data1[i].temperature;}


				}
			}
			xmlhttp.open("GET","/ajaxtest1?q="+str,true);
			xmlhttp.send();

			myChart.setOption(option, true);
		},3000);
		</script>
	</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值