javascript - 尝试使用带有 AJAX 的按钮单击来激活 PHP 功能
问题描述
我正在尝试调用将从 HTML 表中读取数据的 PHP 脚本/文件。我想按下一个按钮,以便 PHP 脚本/文件将激活并将 HTML 表中的数据读取到使用 MySQL 的数据库中。
我的 AJAX 脚本没有激活 PHP 文件。
HTML 按钮代码:
<button type="submit" class="btn btn-md btn-primary btn-block" id="save">Save Workout</button>
AJAX 代码:
$(document).ready(function(){
$("#save").click(function(){
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
}
});
});
});
不完整的 PHP 代码(不包含 DB 代码) - 基于https://brennanhm.ca/knowledgebase/2015/11/import-html-table-into-mysql-table/
<?php
require_once ('simple_html_dom.php');
$table = file_get_html('addWorkout.php');
$db = mysqli_connect('localhost', 'root', '', 'workoutLogger');
foreach($table ->find('tr') as $tr) {
$exercise = $tr->find('td', 0)->plaintext;
$weight = $tr->find('td', 1)->plaintext;
$sets = $tr->find('td', 2)->plaintext;
$reps = $tr->find('td', 3)->plaintext;
$exercise_c = mysqli_real_escape_string($db, $exercise);
$weight_c = mysqli_real_escape_string($db, $weight);
$sets_c = mysqli_real_escape_string($db, $sets);
$reps_c = mysqli_real_escape_string($db, $reps);
}
?>
我无法弹出成功消息。
解决方案
要防止默认的表单提交操作,您只需添加event.preventDefault();
像这样的东西...
$(document).ready(function(){
$("#save").click(function(event){ // must include event here to match the object in the next line. It can be called anything.
event.preventDefault(); // Prevent Default Submit
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
},
error: function (request, status, error) {
alert("ERROR: " + request.responseText);
}
});
});
});
如果由于某种原因禁用了 javascript,您需要决定采取什么措施。到目前为止,您通过添加操作对表单的回答中所拥有的内容,这将是这种情况下的后备。这是你需要思考和决定的事情。
推荐阅读
- java - 模拟大学餐厅的队列
- solr - tf 是如何计算的?
- python - 在pySide2中按下按钮时如何将项目添加到QListWidget?
- swift - swift中的水平Stackview:如何根据内容包装
- ios - 尝试在 iOS 上共享到 Apple Books 时出现 LaunchServices 错误
- python - Python 多处理管理器 - 列表名称错误?
- flutter - Flutter SteamBuilder 快照.data 为空
- python - 如何在 python pandas 中读取大量 excel 文件?
- ios - Swift 5 - 执行 SELECT 后无法将数据插入 SQLite 表
- java - Eclipse 控制台未针对扫描仪/用户输入操作运行