You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Spring Boot控制器将JavaScript变量存入MySQL?含无表单提交场景

没问题,这个需求很常见——咱们完全可以用异步AJAX请求来实现,不用表单提交也能把前端拿到的email_id传给Spring Boot后端,再存到MySQL数据库里。下面我一步步给你拆解实现步骤:

1. 先搭好Spring Boot后端的基础结构

首先得准备好实体类、数据访问层和接收请求的控制器:

实体类(对应MySQL表)

先定义一个和数据库表映射的实体,用来存储邮箱:

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class UserEmail {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String emailId;

    // 无参构造、全参构造、getter和setter
    public UserEmail() {}

    public UserEmail(String emailId) {
        this.emailId = emailId;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getEmailId() { return emailId; }
    public void setEmailId(String emailId) { this.emailId = emailId; }
}

数据访问层(Repository)

用Spring Data JPA简化数据库操作:

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserEmailRepository extends JpaRepository<UserEmail, Long> {
}

控制器(接收前端请求)

写一个REST接口接收前端的邮箱数据,记得处理跨域问题:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "*") // 生产环境建议指定具体前端域名,比如http://your-frontend.com
public class EmailController {

    @Autowired
    private UserEmailRepository emailRepository;

    @PostMapping("/save-email")
    public String saveEmail(@RequestBody EmailRequest emailRequest) {
        // 将邮箱存入数据库
        UserEmail userEmail = new UserEmail(emailRequest.getEmailId());
        emailRepository.save(userEmail);
        return "Email saved successfully!";
    }

    // 内部类用来接收前端的JSON数据
    public static class EmailRequest {
        private String emailId;

        public String getEmailId() { return emailId; }
        public void setEmailId(String emailId) { this.emailId = emailId; }
    }
}

2. 前端用Fetch API发送数据(无需表单提交)

在你FB API的回调函数里,拿到email_id后直接用Fetch API异步发送给后端:

function testAPI() { 
    console.log('Welcome! Fetching your information.... '); 
    FB.api('/me', { locale: 'en_US', fields: 'name, email' }, function(response) { 
        var email_id = response.email; 
        
        // 发送邮箱数据到后端
        fetch('http://your-spring-boot-url:8080/save-email', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ emailId: email_id }),
        })
        .then(response => response.text())
        .then(data => {
            console.log('Success:', data);
            // 成功后更新页面提示
            document.getElementById('status').innerHTML = 'Thanks for logging in, ' + email_id + '! Your email has been saved.';
        })
        .catch((error) => {
            console.error('Error:', error);
            document.getElementById('status').innerHTML = 'Oops, there was an error saving your email.';
        });
    });
}

补充说明

  • 如果前端和后端在同一域名下,把Fetch的URL改成相对路径'/save-email'即可。
  • 生产环境别用@CrossOrigin(origins = "*"),指定具体的前端域名更安全。
  • 你也可以用jQuery的$.ajax()替代Fetch API,写法类似:
$.ajax({
    url: 'http://your-spring-boot-url:8080/save-email',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ emailId: email_id }),
    success: function(data) {
        console.log(data);
        document.getElementById('status').innerHTML = 'Thanks for logging in, ' + email_id + '!';
    },
    error: function(error) {
        console.error(error);
    }
});

内容的提问来源于stack exchange,提问作者Vineet Vinnu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:55:03