原生js 发起ajaxpost请求,服务器从数据库中找数据,如果没有就添加到数据库,如果有,就告诉前端页面有这条数据了
时间: 2024-02-23 16:02:18 浏览: 29
可以使用以下代码实现:
```javascript
var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/data", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
// 处理返回的数据
}
};
var data = JSON.stringify({
"key": "value"
});
xhr.send(data);
```
在服务器端,可以使用Node.js的Express框架来处理请求,具体代码如下:
```javascript
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const MongoClient = require("mongodb").MongoClient;
app.use(bodyParser.json());
app.post("/api/data", function(req, res) {
// 连接到MongoDB数据库
MongoClient.connect("mongodb://localhost:27017", function(err, client) {
if (err) throw err;
const db = client.db("mydb");
const collection = db.collection("mycollection");
// 查找数据
collection.find({key: req.body.key}).toArray(function(err, result) {
if (err) throw err;
if (result.length === 0) {
// 数据库中没有该数据,添加数据
collection.insertOne(req.body, function(err, result) {
if (err) throw err;
console.log("Data added to database.");
res.send("Data added to database.");
});
} else {
// 数据库中已有该数据,返回信息
console.log("Data already exists in database.");
res.send("Data already exists in database.");
}
client.close();
});
});
});
app.listen(3000, function() {
console.log("Server started at http://localhost:3000");
});
```
在服务器端使用MongoDB数据库,首先需要连接到数据库,然后获取到指定的集合,使用find方法查找数据,如果结果为空,说明数据库中没有该数据,使用insertOne方法添加数据,否则说明数据库中已有该数据,直接返回信息即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)