使用HTML按钮执行PHP(jQuery)

时间:2016-02-08 22:24:50

标签: javascript php jquery html ajax

我有一个带有一些按钮的网站和一个显示咖啡机的摄像机流。使用php功能我可以通过TCP / IP消息设置机器开/关。现在我想通过按钮发送/关闭命令,而无需刷新网站。在阅读了一些类似的线程之后,我认识到唯一的方法是使用AJAX。

按下按钮后,页面不会刷新,但似乎背景中的某些内容已完成。但我的“测试”字符串没有显示。

有谁知道我的代码有什么问题? 提前谢谢!

ajax.php

<?php
if($_POST['action'] == 'call_this') {
    echo 'TEST';
}
?>

buttonClick.js

function myAjax() {
  $.ajax({
       type: "POST",
       url: 'ajax.php',
       data:{action:'call_this'},
       success:function(html) {
         alert(html);
       }

  });
}

的index.php

<html>
<head>
    <script src="jquery-1.12.0.min.js"></script>
    <script language="javascript" type="text/javascript" src="buttonClick.js"></script>
</head>
<body>
....
....
<form>
    <input type="submit" name="submit" value="SET ON" onClick="myAjax()">
</form>
....
....
</body>
</html>

3 个答案:

答案 0 :(得分:2)

修改了Mouad Nejjari代码,如下所示

<强>的index.php

    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>   
    </head>
    <body>
    <button id="btnTest">Click</button>
    <script>
    $(document).ready(function () {
    $('#btnTest').click(function () {
    $.ajax({
       type: "POST",
       url: 'ajax.php',
       data:{action:'call_this'},
       success:function(html) {
         alert(html);
       }
     });
    })});    
   </script>
   </body>
   </html>

<强> ajax.php

<?php
if($_POST['action'] == 'call_this') {
    echo 'TEST';
}
?>

答案 1 :(得分:0)

您正在使用类型设置为input的HTML元素submit,这意味着在点击该页面时,您希望重定向到通常在Form标记中提供的处理页面URL。您可以使用PreventDefault()的javascript方法,也可以将表单提交中的元素更改为此类链接。

<html>
<head>
    <script src="jquery-1.12.0.min.js"></script>
    <script language="javascript" type="text/javascript" src="buttonClick.js"></script>
</head>
<body>
....
....
<a href="javascript: myAjax()">SET ON</a>
....
....
</body>
</html>

带有javascript href的链接不会尝试重定向。您的示例在等待php脚本返回之前离开了页面。

答案 2 :(得分:0)

试试这个,ajax.php:

<?php
if($_POST['action'] == 'call_this') {
    echo 'TEST';
}
?>

buttonClick.js:

$(document).ready(function()
{
     $("#form1").submit(function (e) {
            e.preventDefault();
            $.ajax({
           type: "POST",
           url: 'ajax.php',
           data:{action:'call_this'},
           success:function(html) {
             alert(html);
            }
         });
    })
})

index.php:

<html>
<head>
    <script src="jquery-1.12.0.min.js"></script>
    <script language="javascript" type="text/javascript" src="buttonClick.js"></script>
</head>
<body>
....
....
<form id="form1">
    <input type="submit" name="submit" value="SET ON">
</form>
....
....
</body>
</html>