我想調用一個PHP函數,當一個HTML按鈕被點擊。我做了一些搜索,發現它不可能直接做到這一點,我應該使用Ajax。 所以這是我迄今爲止的嘗試,這是不working.this是我的test.php和功能也在這個頁面。php函數調用與AJAX
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.NextPage').on('click', function() {
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
alert(response);
}
});
});
});
</script>
</head>
<body>
<button type="button" class="NextPage">go to nextpage</button>
<?php
if (isset($_POST['x'])) {
if ($_POST['x'] == 1) {
$data = function1();
echo json_encode($data);
exit;
}
}
function function1() {
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>
你的函數將永遠不會被調用,因爲'$ x的值當你的時候總是'0'做比較。你的代碼在語法上也不正確。它應該看起來像:'$('。NextPage')。click(function(){$ .ajax({'。 –
感謝您的快速響應.i按照您所說的編輯了我的代碼,但現在我得到錯誤「未定義的索引:x「在這一行:$ x = $ _POST ['x']; – user3622910