บางครั้งเราจำเป็นต้องทำงานเก็บข้อมูลต่างๆ ไว้ที่ local storage ก่อนเพื่อทำงานหลายอย่าง หรือ หลายๆหน้าเก็บไว้ใน local storage ก่อน หรือ บางครั้งฟอร์มข้อมูลเรามีช่องเก็บข้อมูลมากเกิดไปก็สามารถนำเทคนิคนี้ไปใช้ได้ ครับ (Input form มีขนาดจำกัด)
มาดูกันเลยครับ
ส่วนของ HTML เพือทำฟอร์มแบบนี้ขึ้นมา วิธีใช้คือ พิมค่าในช่อง Username แล้วกด Set LS Javascript ก็จะเก็บข้อมูลไว้ใน local storage ให้เรา
กด ปุ่ม Send To Server ก็จะ POST ค่าไปที่ Server ในที่นี้จะทำตัวรับด้วย PHP
ส่วนของ HTML
โค้ด: เลือกทั้งหมด
<div class="row">
<div class="col-sm-4">
<div class="row">
<label class="col-sm-3" for="username">Username</label>
<div class="col-sm-9">
<input class="form-control text-right" type="text" id="username" />
</div>
<br/><br/>
<div class="col-sm-12 text-right">
<button class="btn btn-default" id="setLS">Set LS</button>
<button class="btn btn-primary" id="sendLS">Send To Server</button>
<button class="btn btn-danger" id="clearLS">Clear LS</button>
</div>
</div>
</div>
</div>
โค้ด: เลือกทั้งหมด
<script>
$(function() {
$('#setLS').click(function(e) {
e.preventDefault();
var username = $('#username').val();
window.localStorage.setItem("PortalLoginApp.userName", username);
});
$('#clearLS').click(function(e) {
e.preventDefault();
localStorage.clear();
$('#username').val('');
});
$('#sendLS').click(function(e) {
e.preventDefault();
var userName = window.localStorage.getItem("PortalLoginApp.userName");
$.ajax({
url: 'post.php',
data: {userName: userName},
type: 'POST'
}).done(function(resp) {
alert(resp);
});
});
});
</script>
โค้ด: เลือกทั้งหมด
post.php
<?php
$username = !empty($_POST['userName']) ? $_POST['userName'] : false;
if ($username) {
echo "Hello, {$username}";
}
else {
echo "Who's there?";
}
ไว้คราวหน้า จะมาแนะนำการ POST ค่าจะจากการเก็บที่ Local Store เป็น array แล้ว Post ให้ Server ทางฝั่ง Python บ้าง