有谁能告诉我,我在这里缺少什么?
这是基本的HTML文件,其中包含一个简单的“创建”和“销毁”按钮,最终将调用API。使用Ajax单击按钮似乎有效,但PHP函数未被调用。
testapi.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
alert("Action performed successfully!");
});
});
});
</script>
</head>
<body>
<input type="submit" class="button" name="create" value="Create" />
<input type="submit" class="button" name="destroy" value="Destroy" />
</body>
</html>
ajax.php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'create':
create();
break;
case 'destroy':
destroy();
break;
}
}
function create() {
echo "Create function.";
exit;
}
function destroy() {
echo "Destroy function.";
exit;
}
答案 0 :(得分:1)
您的情况有误:您输入的值为Create
,而在您的代码中则检查create
。
更改
switch ($_POST['action']) {
case 'create':
create();
break;
case 'destroy':
destroy();
break;
}
到
switch ($_POST['action']) {
case 'Create':
create();
break;
case 'Destroy':
destroy();
break;
}