2017-10-11 143 views
-1

我试图根据不同的按钮点击运行多个php脚本。 当使用点击按钮时,我不希望页面重新加载,只是基本上运行PHP脚本。使用Ajax按钮单击运行多个php脚本点击

这是我的代码,但由于某种原因,我无法得到以下代码来工作。

我想我没有正确调用按钮ID。

<html> 
    <head> 
    <title>Example</title> 


    <script> 


    $('.myButton').click(function() { 

    $.ajax({ 
     type: "GET", 
     url: "run.php" 
    }).done(function(resp) { 
     alert("Hello! " + resp); 
    });  

    }); 

    $('.myButton2').click(function() { 

    $.ajax({ 
     type: "GET", 
     url: "run1.php" 
    }).done(function(resp) { 
     alert("Hello! " + resp); 
    });  

    }); 

    $('.myButton3').click(function() { 

    $.ajax({ 
     type: "GET", 
     url: "run2.php" 
    }).done(function(resp) { 
     alert("Hello! " + resp); 
    });  

    }); 



    </script> 
    </head> 
    <body> 

    <input type="button" value="Click" id="myButton" /> 
    <input type="button" value="Click" id="myButton2" /> 
    <input type="button" value="Click" id="myButton3" /> 

    </body> 
</html> 
+0

这里有没有PHP的,所以为什么标签? –

+0

1)http://idownvotedbecau.se/beingunresponsive 2)http://idownvotedbecau.se/nomcve/ –

回答

0

是的,你没有正确调用按钮。

$('.button') // Calling a button with the button class 
$('#myButton3') // Calling a button with the button id 
1
$('.myButtonx') 

将获得由类名元素,我没有看到添加的按钮任何这样的类。

使用$('#myButton1'), $('#myButton2'), $('#myButton3')你使用过$('.myButton1')$('.myButton2')$('.myButton3'),这应该工作

0

问题:

  1. 要调用使用类点击事件,但没有阶级的存在,所以我改变了代码中使用的ID。
  2. 它是一种很好的方法,你称这些类型的事件为document.ready()
  3. 总是在页面末尾使用javascript,它会减少页面加载时间。

这里是工作示例:

<html> 
    <head> 
    <title>Example</title> 


    </head> 
    <body> 

    <input type="button" value="Click" id="myButton" /> 
    <input type="button" value="Click" id="myButton2" /> 
    <input type="button" value="Click" id="myButton3" /> 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

    <script> 


    $(document).ready(function() { 
     $('#myButton').click(function() { 

     $.ajax({ 
      type: "GET", 
      url: "run.php" 
     }).done(function(resp) { 
      alert("Hello! " + resp); 
     });  

     }); 

     $('#myButton2').click(function() { 

     $.ajax({ 
      type: "GET", 
      url: "run1.php" 
     }).done(function(resp) { 
      alert("Hello! " + resp); 
     });  

     }); 

     $('#myButton3').click(function() { 

     $.ajax({ 
      type: "GET", 
      url: "run2.php" 
     }).done(function(resp) { 
      alert("Hello! " + resp); 
     });  

     }); 
    }); 



    </script> 

    </body> 
</html> 
+0

仍然不工作我的朋友,这是正确的做法? – user1457821

+0

是的,我在我的机器上运行了这个 –

+0

什么不适合你的机器?如果发送ajax请求,您可以请检查开发人员工具吗? –