ajax๋ก Post ์์ฒญํ๊ธฐ
ajax๋ก Post ์์ฒญํ๊ธฐ
ajax๋ฅผ ์ด์ฉํด์ ์๋ฒ์ Post ์์ฒญ์ ํด๋ณด์.
๋ก๊ทธ์ธ ํ์ด์ง
<div class="container">
<form>
<div class="form-group">
<label for="username">UserName:</label>
<input type="text" class="form-control" placeholder="Enter UserName" id="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" placeholder="Enter password" id="password">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" placeholder="Enter email" id="email">
</div>
</form>
<button id="btn-save" class="btn btn-primary">ํ์๊ฐ์
</button>
</div>
์์ ๊ฐ์ด ์ฌ์ฉ์ ์ด๋ฆ, ๋น๋ฐ๋ฒํธ, ์ด๋ฉ์ผ ์ฃผ์๋ฅผ ์ ๋ฌํ๋ ํ์๊ฐ์ ํ์ด์ง์ container๊ฐ ์๋ค๊ณ ํ์.
์๋๋ method="post"
๋ฐฉ์์ผ๋ก ์๋ฒ์๊ฒ ํฌ์คํธ ์์ฒญํ์ง๋ง, ์ฌ๊ธฐ์ ajax๋ฅผ ํ์ฉํด์ ์์ฒญํด๋ณด์.
์ปจํ
์ด๋ ํ๋จ์ <script src="js ์ฃผ์"></script>
๋ฅผ ๋ง๋ค์ด์ฃผ๊ณ js ํ์ผ์ ๋ง๋ ๋ค.
js ํ์ผ
let index = {
init: function () {
$("#btn-save").on("click", () => {
this.save();
});
},
save: function () {
let data = {
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val(),
};
$.ajax({
type: "POST",
url: "/blog/api/user",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
}).done(function (response) {
alert('ํ์๊ฐ์
์ด ์๋ฃ๋์์ต๋๋ค.');
location.href="/blog";
}).fail(function (error) {
alert(JSON.stringify(error));
});
},
};
index.init();
ํ๋์ฉ ์์๋ณด์.
javascript ์์ค
let index = ...
js ํ์ผ ๊ฐ์ ๊ฐ์ฒด ์ด๋ฆ์ ์ค๋ณต์ ํผํ๊ธฐ ์ํด ๋ณดํต ์ด๋ ๊ฒ ๊ฐ์ฒด๋ฅผ ์ ์ธํ๊ณ index.init();
์ ๋ฐฉ์์ผ๋ก ์์ํ๋ค.
$("#btn-save").on("click", () => {
this.save();
});
arrow function์ ์จ์ this๋ฅผ ๋ฐ์ธ๋ฉ ํ๋ค. ์ฌ๊ธฐ์์ this๋ index์ด๋ค.
function()์ ์ฌ์ฉํด์ save๋ฅผ ํธ์ถํ๊ณ ์ถ๋ค๋ฉด, index ์๋์ _this๋ฅผ ์ ์ธํด์ ์ฌ์ฉํ ์๋ ์๋ค.
$.ajax({ ...
ajax๋ฅผ ํธ์ถํ๋ ๋ถ๋ถ์ด๋ค. ๊ธฐ๋ณธ์ ์ผ๋ก ๋น๋๊ธฐ ํธ์ถ์ด๋ค.
type: "POST",
url: "/blog/api/user",
data: JSON.stringify(data),
์์ฒญ ํ์
์ POST
, ์์ฒญ์ ํ๋ url, http body์ ๋ณด๋ผ ๋ฐ์ดํฐ๋ฅผ ์
๋ ฅํ๋ค.
contentType: "application/json; charset=utf-8",
body ๋ฐ์ดํฐ๊ฐ ์ด๋ค MIMETYPE ์ธ์ง ์ ์ธํ๋ค.
location.href="/blog";
ํ์๊ฐ์
์ด ์๋ฃ๋๋ฉด ์๋ฒ๊ฐ ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํ๊ณ , ํด๋ผ์ด์ธํธ ์
์ฅ์์ ์๋ก์ด ํ๋ฉด์ด ๋์์ผ ํ๋ฏ๋ก location.href
๋ฅผ ์ด์ฉํ๋ค.