Summary | jQuery $ajax sample or snippet |
Env | jQuery |
Last active
October 9, 2015 03:36
-
-
Save fliedonion/bedb5d85042e9379d72b to your computer and use it in GitHub Desktop.
jQuery-$ajax-sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head lang="en"> | |
<meta charset="UTF-8"> | |
<title></title> | |
</head> | |
<body> | |
<div id="printArea">press button, display return value here.</div> | |
<br/> | |
<button id="postData">post</button> | |
<br/> | |
<button id="getData">get</button> | |
<br/> | |
<script src="bower_components/jquery/dist/jquery.min.js"></script> | |
<!-- | |
"dependencies": { | |
"jquery": "~2.1.4" | |
} | |
--> | |
<script> | |
function handleError(response){ | |
console.log(response); | |
alert("error: " + response.status); | |
} | |
$(function(){ | |
$('#getData').click(function(){ | |
console.log('getData pressed'); | |
$.ajax({ | |
url: 'http://localhost:3000/get-req', | |
type: 'get', | |
dataType: 'json', | |
data: { id: "get" } | |
}).then(function success(response){ | |
$('#printArea').text(response.sent); | |
}, handleError); | |
}); | |
$('#postData').click(function(){ | |
console.log('postData pressed'); | |
$.ajax({ | |
url: 'http://localhost:3000/post-req', | |
type: 'POST', | |
dataType: 'json', | |
contentType: 'application/json; charset=utf-8', | |
data: JSON.stringify({ id: "post" }) | |
}).then(function success(response){ | |
$('#printArea').text(response.sent); | |
}, handleError); | |
}); | |
}) | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "dependencies": { | |
// "cors": "^2.7.1", | |
// "body-parser": "^1.14.1", | |
// "express": "^4.13.3" | |
// }, | |
// "devDependencies": { | |
// "nodemon": "^1.7.1" | |
// }, | |
var express = require('express'); | |
var cors = require('cors'); | |
var bodyParser = require('body-parser'); | |
var app = new express(); | |
app.use(cors()); | |
app.use(bodyParser.json()); | |
app.get('/get-req', function(req, res){ | |
res.json({ret: "get request", sent: req.query.id }); | |
}); | |
app.post('/post-req', function(req, res){ | |
res.json({ret: "post request", sent: req.body.id}); | |
}); | |
app.listen(3000, function(){ | |
console.log('server running on localhost:3000') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment