[英]PHP function doesn't work with Ajax
我有一些按鈕,然后單擊JS:
<button id="trigger">Send</button>
和JS調用簡單的動作
$('#trigger').on("click", function(event){
jQuery.ajax({
type: "POST",
url: 'functions.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
alert('test success');
},
complete: function (obj, textstatus) {
alert('test complete');
}
});
});
在上面的ajax中,我將functions.php與其他簡單函數放在一起:
<?php
$message = "PHP Funtion Alert";
echo "<script type='text/javascript'>alert('$message');</script>";
?>
但是,我只從alert('test complete');中調用了Alert。 如何從PHP文件調用警報?
PS。 這僅是示例。 在PHP文件中將包含一些DB函數。
您期望使用JSON,因此
dataType: 'json',
但是,您要返回腳本標簽嗎?
echo "<script type='text/javascript'>alert('$message');</script>";
那是一個錯誤。 您想要的是返回有效的JSON
$message = array("message" => "PHP Funtion Alert");
echo json_encode($message);
然后抓住ajax函數
jQuery.ajax({
type : "POST",
url : 'functions.php',
dataType : 'json',
data : {
data : 'to be sent'
}
}).done(function(data) {
console.log(data.message);
}).fail(function() {
console.log(arguments);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.