如何使用jQuery Post和Java在PostgreSQL中保存json数据?
我想在单击Submit按钮后,使用jQuery(在post请求时使用ajax调用)和Java将json数据对象保存到Postgresql中,请帮助我这样做?提前谢谢 html:如何使用jQuery Post和Java在PostgreSQL中保存json数据?,java,jquery,json,ajax,postgresql,Java,Jquery,Json,Ajax,Postgresql,我想在单击Submit按钮后,使用jQuery(在post请求时使用ajax调用)和Java将json数据对象保存到Postgresql中,请帮助我这样做?提前谢谢 html: (function() { var testValue; testValue = {}; $('input[id=buttonId]').click(function() { var name; name = $(this).attr('name'); testValue[name]
(function() {
var testValue;
testValue = {};
$('input[id=buttonId]').click(function() {
var name;
name = $(this).attr('name');
testValue[name] = $(this).val();
});
$('#submit').click(function() {
$('input[id=fileId]').each(function($i) {
var name;
name = $(this).attr('name');
testValue[name] = $(this).val();
});
console.log(JSON.stringify(testValue));//it gives the json data object, after clicking on Submit button`[ex: {"firstButton":"button1","secondButton":"button2","file":"test.txt"} ]`
});
})();
Postgresql表:创建表savedata(id整数主键,内容json)代码>
证书:
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://localhost:5432/dbname"
db.default.user=test
db.default.password=test
html:
首先,我将用java编写一个程序,稍后它将接受来自javascript的POST请求。您还可以在其中添加某种形式的记录,这样不是每个人都可以添加记录。你也可以用我会用的
一旦POST请求包含JSON数据和所需授权,您就可以让Java解析JSON以插入数据库的语句
现在是Javascript部分:最好使用ajax发送JSON编码的数据。使用POST请求
在这种情况下,它看起来像
使用:
-
jQuery
//POST JSON data to the API
$.post( "youdomain.com/message", JSON.stringify(yourDataObjectOrArray));
谢谢@Thomas的回复,是的,前端可以是Javascript/AngularJS/jQuery,后端可以是Java/Scala和Postgresql数据库。@Thomas有Java后端的Javascript前端没有什么不清楚的地方。事实上,这很常见。
// Create a method that handles a POST request. In this case to "/message"
@POST("/message/}")
public Message insertInDb(Message msg // body param
) {
// Decode the JSON to an array object so you can loop it for insert statement(s)
JSONArray json = new JSONArray(msg);
/////////////////////////////////////////////////////////////////////
// Create the postgre connection
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"manisha", "123");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
// Use the JSON data instead below for the INSERT statement:
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
+ "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
c.close();
} catch (Exception e) {
return e.getClass().getName()+": "+ e.getMessage();
}
return "success";
}
//POST JSON data to the API
$.post( "youdomain.com/message", JSON.stringify(yourDataObjectOrArray));