[英]how to call one function in another php file by using ajax
<script>
$(document).ready(function(){
$("#amount").on('click', function(){
var amount = this.value;
$.ajax({
url: "ipg-util.php/createHash",
type: 'post',
data: { "amount": amount
},
success: function(response) { console.log(response); }
});
});
});
</script>
您可以簡單地將Method to Call
作為data
屬性的一部分傳遞,如下所示:
<script>
$(document).ready(function(){
$("#amount").on('click', function(){
var amount = this.value;
$.ajax({
url: "ipg-util.php",
type: 'post',
data: { "amount": amount, "callable": "createHash"},
success: function(response) { console.log(response); }
});
});
});
</script>
然后在ipg-util.php
里面你可以做這樣的事情:
<?php
$callable = isset($_POST['callable']) ? $_POST['callable'] : "default";
$amount = isset($_POST['amount']) ? $_POST['amount'] : null;
switch($callable){
case "createHash":
$response = createHash(); // CALL createHash METHOD DEFINED HEREIN
break;
case "doAnotherThing":
$response = doAnotherThing(); // CALL doAnotherThing METHOD DEFINED HEREIN
break;
default:
$response = default(); // CALL default METHOD DEFINED HEREIN
break;
}
die(json_encode($response));
function createHash(){
}
function doAnotherThing(){
}
function default(){
}
$.ajax調用服務器上下文或 URL,無論調用特定的“操作”。 你想要的是像下面的代碼如下:
$.ajax({ url: '/demo/websitepage',
data: {action: 'calltofunction'},
type: 'POST',
success: function(output) {
alert(output);
}
});
在服務器端,應該讀取動作 POST 參數,並且相應的值應該指向要調用的方法,以下代碼用於執行此操作:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'calltofunction' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
希望這將是一個更好的參考: https : //en.wikipedia.org/wiki/Command_pattern
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.