使用Ajax按钮单击运行多个php脚本

时间:2017-10-11 18:59:02

标签: jquery ajax

我试图根据不同的按钮点击运行多个PHP脚本。 当使用点击按钮时,我不想重新加载页面,只是基本上运行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>

3 个答案:

答案 0 :(得分:1)

$('.myButtonx')

将按类名获取元素,并且我没有看到任何此类添加到按钮中。

使用$('#myButton1'), $('#myButton2'), $('#myButton3')您已使用$('.myButton1')$('.myButton2')$('.myButton3')的地方,这应该有效

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

问题:

  1. 您正在使用类调用click事件,但不存在该类,因此我更改了代码以使用ID。
  2. 这是一种在document.ready()
  3. 上称为此类事件的好方法
  4. 始终在页面末尾使用javascript,这会减少页面加载时间。
  5. 以下是工作示例:

    <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>
    
相关问题