2017-06-14 157 views
0

我有2個腳本,submit.phpdisplay.php簡單的PHP AJAX腳本

我希望能夠加載submit.php,點擊提交按鈕&將result格顯示爲123

現在,它只是重新加載我的網頁。我沒有從我的控制檯得到任何東西,所以堅持如何調試。

有人可以看看並提供幫助嗎?

submit.php:

<form> 

    <input type="submit" value="Submit" name="display" id="display"> 

</form> 

<div id="result">&nbsp;</div> 

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
<script type="text/javascript"> 
$("#display").click(function() {     

    $.ajax({ 
     url: 'display.php', 
     type: 'GET',   
     dataType: "html", 
     data: { 
     "id": "123", 
     }, 
     success: function(data) { 
     //called when successful 
     $('#result').html(data); 
     }, 
     error: function(e) { 
     //called when there is an error 
     //console.log(e.message); 
     } 
    }); 

}); 
</script> 

Display.php的:

<?php 
$id = $_GET['id']; 
echo $id; 
?> 
+2

變化'類型= 「提交」''給類型= 「按鈕」'。您只需提交表單並重新加載頁面。您需要防止提交表單。 – j08691

+0

@ j08691我相信即使那樣,它也會重新加載它。 –

+1

@PraveenKumar如果輸入不是提交按鈕,爲什麼會重新加載? – j08691

回答

3

它提交或重新加載頁面。您需要防止默認操作。更改前兩行:

$("#display").click(function(e) { // Add e (event) parameter. 
    e.preventDefault();    // Prevent the default action for this event. 

可能變化type="button",但不知道這是否是有效的。

+3

*「您可以更改爲type =「button」,但不知道它是否有效。「* - 我確定它會;-) –

+1

它肯定是 - 只是測試它:) – michaelmcgurk

+1

@michaelmcgurk LoL。感謝您的確認。 ':)'我在執行它時遇到了問題。我應該搞點東西或者想念一些東西。 –

0

解決您的問題,請

replace 
<input type="submit" value="Submit" name="display" id="display"> 
    by 

    <button type="button" name="display" id="display">Submit</button>