just started using node+express, to use static page request ajax to have a problem, but the current result is:
1. The first request does not enter success, printing undefined;
2. When the second request starts, enter success, to print the result of the first request;
3. The third request prints the result of the second request, but looking at the background transmission value, it is found that there is no problem with the transmitted value, but there is a problem with the received value
how to solve this problem?
app.js code is:
var mysql = require("mysql");
var express = require("express");
var app = express();
var settings = require("./build/db");
app.use(express.static("./src"));
//
var connection = mysql.createConnection(settings.db);
connection.connect(function(err){
if(err){
console.log("[query] - :"+err);
}else{
console.log("[connection connect] succeed!");
}
});
//
var arr=[];
//
app.get("/getname", function(req, res) {
var selectSQL = "select linkname from `mkln_server_contract`";
connection.query(selectSQL, function(err, rows) {
if (err) throw error;
for (var i = 0; i < rows.length; iPP) {
arr[i] = rows[i].linkname;
}
console.log(arr[1]);
});
res.send(arr);
});
app.post("/getid", function(req, res) {
var selectSQL = "select id from `mkln_server_contract`";
connection.query(selectSQL, function(err, rows) {
if (err) throw error;
for (var i = 0; i < rows.length; iPP) {
arr[i] = rows[i].id;
}
console.log(arr[1]);
});
res.send(arr);
});
//
//connection.end();
app.listen(3000);
html
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery-1.12.0.js"></script>
<script src="js/index.js"></script>
<style>
-sharpuid{
margin-left:40px;
}
</style>
</head>
<body>
<button id="name"></button>
<button id="uid">ID</button>
</body>
js
$(function() {
$("-sharpname").click(function() {
$.ajax({
type: "GET",
url: "getname",
success: function(data) {
console.log(data[1]);
},
error : function (err) {
console.log("error : " + err);
}
});
});
$("-sharpuid").click(function() {
$.ajax({
type: "POST",
url: "getid",
success: function(data) {
console.log(data[1]);
},
error : function (err) {
console.log("error : " + err);
}
});
});
});