歡迎大家,請告訴我如何將新的描述從 Ajax 表單發送到資料庫?并將其帶回頁面上顯示?
當您單擊“提交”按鈕時,將向 send_description 函式發送一個 ajax 請求。在這個函式中,據我了解,需要將輸入值寫入資料庫并回傳給頁面
頁面截圖
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax</title>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
</head>
<body>
<div class="setting" style="width: 400px; border: 1px solid red; padding: 20px; margin-bottom: 50px;">
<form method="post" id="form">
<span>Current description: <textarea name="new_description"></textarea></span>
<button type="submit">Save</button>
</form>
</div>
<div class="output" style="width: 400px; border: 1px solid green; padding: 20px;">
<span>Description: <b>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </b></span>
</div>
<script>
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
var formData = new FormData(document.getElementById("form"));
$.ajax({
url: 'index/get_description',
data: formData,
method: 'POST',
dataType: 'json',
processData: false,
contentType: false,
success: function(data){
console.log(data);
}
});
return false;
});
});
</script>
</body>
</html>
<?php
// connect mysql
$db = new mysqli('localhost', 'root', '', 'test_ajax');
if ($db -> connect_errno) {
echo 'missing database connection!';
} else {
echo 'successfully connected to the database';
}
// function
function send_description() {
$sql = 'SELECT * FROM store';
// 1) Записать новое описание в таблицу
// 1) Write a new description to the table
// 2) Вернуть наше новое описание чтобы отобразить на странице
// 2) Return our new description to display on the page
}
?>
在資料庫中,“store”表,“description”列 截圖來自資料庫
uj5u.com熱心網友回復:
可以這樣做:
你形成
<form method="post" id="form">
<span>Current description:
<textarea name="description"></textarea>
</span>
<button type="submit">Save</button>
</form>
你的js腳本
<script>
$(function(){
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'index/get_description', // you url php script
data: $(this).serialize(),
method: 'POST',
dataType: 'json',
success: function(data){
console.log(data);
}
});
return false;
});
});
</script>
你的php代碼
<?php
$db = new mysqli('localhost', 'root', '', 'test_ajax');
if (!$db->connect_errno) {
echo 'error connected to the database';
die();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$db->query("INSERT INTO store SET description = '{$_POST['description']}'"); // insert in table
$result = $db->query("SELECT * FROM store"); // get from table
$result = $result->fetch_row(); // get array from result
echo json_encoder($result); // retun data for ajax
die();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/438128.html
上一篇:MYSQL中兩個結果的區別
下一篇:從兩個表中獲取每日報告
