问题
I want to make a single page app. simplification of what I want: First on "/"
will be a home page with a display section with 2 buttons. when they click on button 1 we will retrieve data from server and display it on the page in the display section and do the same thing for button 2 but for different data.
I'm having a hard time grasping on how to put in the right display section.
I know you could do conditions in Jade like:
html
head
script(src ="http://code.jquery.com/jquery-2.1.1.js")
script(src = "script.js")
body
p= test
if test == "face"
div.fillIn(style="background:blue; width:400; height:200")
if age
div.fillIn(style="background:red; width:400; height:200")
button(value="send").send send
button(value="change").change change
how do I put in the different variables for age and test? in the server I'm having trouble changing the variable after post request. should be trying to do that?
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var name;
var age;
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.use(express.static("public"))
app.set("view engine", "jade")
app.get("/", function(req, res){
// if(age){
res.render("index",{test: "fac", age: age })
// }
})
//The server script that reads the paramater from the jQuery AJAX and returns the result
app.post("/some", function(req, res){
console.log(req.body)
age = req.body.age
res.send(req.body.name + " and " + req.body.age)
})
......
(I way I was thinking about doing it).I want to make it so that when the button is clicked it retrieves new data and it updates a variable so I could pass it along to Jade so it could update the proper display
button stuff in script.js
$("button.send").on("click", function(){
$.ajax({
method : "POST",
url : "/some",
data : {name : Math.floor(Math.random() * 20), age :"42"},
success : function(data){
$(".fillIn").html(data)
}
})
EDIT:
what I was thinking of doing was to have a 2 different AJAX calls for 2 different buttons each outputting 2 different data like above data : {name : Math.floor(Math.random() * 20), age :"42"}
and the other one would be data : {name : Math.floor(Math.random() * 20), age :"--->43<---"}
. what this does I think will in fill text in the .fillin
div but I don't want to just fill in the div I want a whole other fillin
div. One button will cause the div to have other specif text(HTML) that the user could read plus the data and the other button will do the same with other html element and that specific data. I wish there was a way to pass in a template. that's what I was trying to simulate by having 2 condition divs. I'm not trying to do something for a specific user at this point. I'm just thinking if I could do data : {name : Math.floor(Math.random() * 20), age :"42 | 43"},
for both buttons. I'm passing a long data and I want to say which div to display.
来源:https://stackoverflow.com/questions/34711376/using-ajax-with-express-changing-variables-after-request