我正在尝试调用一个PHP脚本/文件,该脚本/文件将从HTML表中读取数据。我想按下一个按钮,以便PHP脚本/文件将被激活,并使用MySQL将HTML表中的数据读入数据库。
我的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代码(不包含数据库代码)-基于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);
}
?>
我无法弹出成功消息。
答案 0 :(得分:0)
在您的PHP中,“ $ table”和“-> find('tr')”之间有一个空格,这会在脚本中产生错误并导致AJAX返回失败而不是成功。要获取错误报告并开始进行故障排除,请将AJAX更改为以下内容:
$(document).ready(function(){
$("#save").click(function(){
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
},
error: function (request, status, error) {
alert("ERROR: " + request.responseText);
}
});
});
});
答案 1 :(得分:0)
我最终要做的是使用动作“ addWorkoutTEST.php”来保持按钮的形状并将其包装在表单周围,
[CreateAssetMenu(fileName = "CoinsSystem", menuName = "MyFirstGame/Systems/Coins system", order = 1)]
public class CoinsSystem : ScriptableObject
{
private Action<int> onCoinsUpdated;
public void BuyCoins(int amount)
{
var numCoins = PlayerPrefs.GetInt("num_coins");
numCoins += amount;
PlayerPrefs.SetInt("num_coins", numCoins);
onCoinsUpdated?.Invoke(numCoins);
}
public void SpendCoins(int amount)
{
var numCoins = PlayerPrefs.GetInt("num_coins");
numCoins -= amount;
if (numCoins < 0)
numCoins = 0;
PlayerPrefs.SetInt("num_coins", numCoins);
onCoinsUpdated?.Invoke(numCoins);
}
public void Subscribe(Action<int> callback)
{
onCoinsUpdated += callback;
}
public void Unsubscribe(Action<int> callback)
{
if (onCoinsUpdated != null)
onCoinsUpdated -= callback;
}
}
答案 2 :(得分:0)
要阻止默认的“表单提交”操作,您只需添加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,则需要确定要采取的措施。到目前为止,您已经通过添加操作对表单做出了回答,这将是这种情况下的后备方法。这是您需要考虑并做出决定的事情。