2017-10-11 86 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請求,您可以請檢查開發人員工具嗎? –