Ajax PHP表单按钮[重复]
This question already has an answer here:
Can anyone tell me what I am missing here please?
Here is the basic HTML file with a simple "Create" and "Destroy" button that will eventually call an API. The button click with Ajax seems to work, but the PHP function is not being called.
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;
}
</div>
此问题已经存在 这里有一个答案: p>
-
参考 - 这个错误在PHP中意味着什么?
34答案
\ n span>
li>
ul>
div>
有人能告诉我这里缺少什么吗? p >
这是基本的HTML文件,其中包含一个简单的“创建”和“销毁”按钮,最终将调用API。 使用Ajax单击按钮似乎有效,但PHP函数未被调用。 p>
testapi.html em> strong> p>
&lt; html&gt; &lt; head&gt; &lt; script src =“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min。 js“&gt;&lt; / script&gt; &lt; script&gt; $(document).ready(function(){ $('。button')。click(function(){ var clickBtnValue = $( 这个).val(); var ajaxurl ='ajax.php', data = {'action':clickBtnValue}; $ .post(ajaxurl,data,function(response){ alert(“ 动作成功执行!“); }); }); }); &lt; / script&gt; &lt; / head&gt; &lt; body&gt; &lt; input type =”submit “class =”button“name =”create“value =”Create“/&gt; &lt; input type =”submit“class =”button“name =”destroy“value =”Destroy“/&gt; &lt; /体&GT; &LT; / HTML&GT; 代码> PRE>
ajax.php EM> 强> p> \ n
if(isset($ _ POST ['action'])){ switch($ _POST ['action']){ case'create': create(); break; case'troy': destroy(); break; } } 函数create(){ echo“创建函数 。;; 退出; } 函数destroy(){ echo“销毁函数。”; 退出; } code> pre> div>
Your case is wrong: the value in your input is Create
, while in your code you check for create
.
Change
switch ($_POST['action']) {
case 'create':
create();
break;
case 'destroy':
destroy();
break;
}
to
switch ($_POST['action']) {
case 'Create':
create();
break;
case 'Destroy':
destroy();
break;
}