[英]Trying to call PHP function using jQuery.post()
這是我的index.php
:
<?php
function type_my_text(){
echo filter_input(INPUT_POST, 'textfield')
}
$action = filter_input(INPUT_POST, 'action');
if($action == "typer"){
type_my_text();
}
?>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
function call_typer(){
$.post('index.php', {action : "typer"});
};
</script>
</head>
<body>
<form name="form" method="POST" action="index.php">
<input type="text" name="textfield">
<input type="submit" value="type" onclick="call_typer()">
</form>
</body>
</html>
使用此代碼,當我單擊“提交”按鈕時,我試圖使用ajax(在這種情況下為post()
調用type_my_text
PHP函數。 我根據其他答案安裝了此代碼,但是它不起作用,我也不知道缺少什么。
過程:
html button click
-> call js call_typer() function
-> make jQuery.post() ajax request
-> php var $action receive "typer"
-> call php function type_my_text()
我希望這段代碼可以在頁面上寫出我在文本字段中寫的內容。 當我提交按鈕時,什么也沒有發生。 我認為ajax請求正在發生,但是filter_input(INPUT_POST, 'action')
卻什么也沒有收到我所期望的( "typer"
作為值)。
沒有出現任何錯誤。
您的$.post()
是對index.php
的AJAX請求。 每當您發出AJAX請求或任何HTTP請求時,瀏覽器都會向服務器(一個托管index.php
)發送HTTP請求,並返回一些數據。 在HTTP AJAX請求的特殊情況下,瀏覽器異步發送HTTP請求而無需刷新頁面,並且在后台從服務器接收響應。
jQuery中的典型AJAX POST調用應如下所示:
$.post("index.php", {action: 'typer'}, function( data ) {
// do something with data, e.g.
console.log(data);
});
然后,您的服務器文件( index.php
)應該向AJAX請求返回一些數據。 因為您已經使用index.php
來提供AJAX數據和普通HTML,所以它看起來應該像這樣:
<?php
function type_my_text() { ... }
// Either serve data to AJAX call, or serve HTML of index page.
if ($_POST['action'] == "typer"){
// serve AJAX call
type_my_text();
}
else {
// serve HTML
?>
<html>
...
</html>
<?php
}
但這很混亂。
最好將關注點分開使用-僅將HTML文件用於提供HTML服務,而將PHP僅用於提供AJAX內容。 換句話說,獲取您的HTML並將其放入index.html
,然后創建ajax.php
(或您想要的任何名稱),然后將您的PHP代碼放入其中。 然后,您將不需要做上述丑陋的事情-在PHP文件中混合HTML代碼。 當然,請記住在JS中更改URL。
額外:
在您的JS提出AJAX請求時,請確保您阻止提交表單的默認瀏覽器操作 -這是一個全新的頁面請求。 否則,您根本就不會做AJAX。
在jQuery中最干凈的方法:
$('#my-form').on('submit', function(e) {
e.preventDefault(); // important - to prevent page refresh
$.post(...); // the AJAX call here
});
然后在您的HTML中:
<form id="my-form">
<input type="text" name="textfield">
<input type="submit">
</form>
要注意的主要事項:
給您的表單一個ID,以便您可以在jQuery中高效地找到它。 無需采取任何其他措施。
我想您會在AJAX之后對textfield
輸入進行某些操作。
避免使用內聯JS。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.