简体   繁体   English

使jQuery AJAX调用特定的PHP函数

[英]Make jQuery AJAX Call to Specific PHP Functions

I am a rookie PHP developer. 我是一名新手PHP开发人员。

I have created a PHP web project with an HTML page that contains an 'Add' button. 我创建了一个PHP Web项目,其中包含一个包含“添加”按钮的HTML页面。 The name of the page is awards.html. 该页面的名称是awards.html。 The awards.html file contains its counterpart JavaScript file, awards.js. awards.html文件包含其对应的JavaScript文件awards.js。 A code is executed in this js file when the Add button is clicked. 单击“添加”按钮时,将在此js文件中执行代码。 This code sends an AJAX call to a PHP class located in /controller/ folder in the project named, Award.php. 此代码将AJAX调用发送到名为Award.php的项目中位于/controller/文件夹中的PHP类。 This PHP file which contains code to execute a function called, addFunction() in another Award.php file located in /model/ folder in the project, which returns a JSON array and is displayed in the awards.html page. 这个PHP文件包含执行名为addFunction()的函数的代码,该函数位于项目的/model/文件夹中的另一个Award.php文件中,该文件返回一个JSON数组并显示在awards.html页面中。

The source code of my files is given as follows: 我的文件的源代码如下:

Awards.html Awards.html

<div class = "divbottom">
    <div id="divAddAward">
        <button class="btn" onclick="onAdd();">Add</button>
    </div>
</div>

awards.js awards.js

function onAdd() {
    $("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
    $.post(
            'classes/Award.php'
            ).success(function(resp) {
        json = $.parseJSON(resp);
    });
}

Award.php (located in /controller/ folder) Award.php(位于/controller/文件夹中)

<?php

foreach (glob("../model/community/*.php") as $filename) {
    include $filename;
}

$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);

Award.php (located in /model/ folder) Award.php(位于/model/文件夹中)

<?php

class Award
{
    public function addFunction() {
        $array = array(
            'status' => '1'
        );
        return $array;
    }
}

My code works perfectly and is error-free. 我的代码完美无缺,并且没有错误。 Now I want to add another button in awards.html called, Save which when clicked will call a function onSave() in the JS file. 现在我想在awards.html中添加另一个名为Save的按钮,单击该按钮将在JS文件中调用函数onSave()。 Thus the source code of my files will change to the following: 因此,我的文件的源代码将更改为以下内容:

awards.html awards.html

<div class = "divbottom">
    <div id="divAddAward">
        <button class="btn" onclick="onAdd();">Add</button>
        <button class="btn" onclick="onSave();">Save</button>
    </div>
</div>

awards.js awards.js

function onAdd() {
    $("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
    $.post(
            'classes/Award.php'
            ).success(function(resp) {
        json = $.parseJSON(resp);
    });
}

function onSave() {
    $("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
    $.post(
            'classes/Award.php'
            ).success(function(resp) {
        json = $.parseJSON(resp);
    });
}

Now the problem here is that since I want to call the same Award.php file from JS, how do I modify my controller Award.php file? 现在问题是因为我想从JS调用相同的Award.php文件,如何修改我的控制器Award.php文件? In my opinion there should be twoo different functions which would contain code to instantiate the view Award.php class and call a different function; 在我看来,应该有两个不同的函数,它们包含实例化视图Award.php类的代码并调用另一个函数; something like the following: 类似以下内容:

Award.php Award.php

<?php

foreach (glob("../model/community/*.php") as $filename) {
    include $filename;
}

function add(){
    $award = new Award(); //Instantiating Award in /model/ folder
    $method = $award->addFunction();
    echo json_encode($method);
}

function save(){
    $award = new Award(); //Instantiating Award in /model/ folder
    $method = $award->saveFunction();
    echo json_encode($method);
}

Award.php Award.php

class Award
{
    public function addFunction() {
        $array = array(
            'status' => '1'
        );
        return $array;
    }

    public function saveFunction() {
        $array = array(
            'status' => '2'
        );
        return $array;
    }
}

But how do I call these specific PHP functions from my JS file? 但是如何从我的JS文件中调用这些特定的PHP函数? If the code I have assumed above is correct, then what should be my JS code? 如果我上面假设的代码是正确的,那么我的JS代码应该是什么? Can anyone please advise me on this? 任何人都可以告诉我这个吗? Replies at the earliest will be highly appreciated. 最早的回复将受到高度赞赏。 Thank you in advance. 先感谢您。

Okay I found the solution to the problem myself. 好吧,我自己找到了问题的解决方案。

I sent a GET-type AJAX call with the data passed in the form of String parameters and added a success property to get a confirmation whether my code has worked or not. 我发送了一个GET类型的AJAX调用,其中包含以String参数形式传递的数据,并添加了一个成功属性,以确认我的代码是否有效。 I also changed my Award.php code to catch the passed parameter successfully. 我还更改了我的Award.php代码以成功捕获传递的参数。

So the source code of my files is: 所以我的文件的源代码是:

awards.js awards.js

function onAdd() {
    $("#display").load(filePath);
    $.ajax({
        type: "GET",
        url: 'controller/Action.php',
        data: "functionName=add",
        success: function(response) {
            alert(response);
        }
    });
}

function onSave() {
    $("#display").load(filePath);
    $.ajax({
        type: "GET",
        url: 'controller/Action.php',
        data: "functionName=save",
        success: function(response) {
            alert(response);
        }
    });
}

Award.php Award.php

$functionName = filter_input(INPUT_GET, 'functionName');

if ($functionName == "add") {
    add();
} else if ($functionName == "save") {
    save();
}

function add()
{
    $award = new Award();
    $method = $award->addFunction();
    echo json_encode($method);
}

function save()
{
    $award = new Award();
    $method = $award->saveFunction();
    echo json_encode($method);
}

You would be better off using an MVC framework in which you can have controller functions for add and save functionality. 您最好使用MVC框架,您可以在其中使用控制器功能来添加和保存功能。 You can achieve the required behavior with your current implementation by sending a query string parameter to tell your php script which function to call: 您可以通过发送查询字符串参数来告诉您的php脚本调用哪个函数,从而在当前实现中实现所需的行为:

<?php

foreach (glob("../model/community/*.php") as $filename) {
    include $filename;
}

function add(){
    $award = new Award(); //Instantiating Award in /model/ folder
    $method = $award->addFunction();
    echo json_encode($method);
}

function save(){
    $award = new Award(); //Instantiating Award in /model/ folder
    $method = $award->saveFunction();
    echo json_encode($method);
}

if($_GET["action"] == "save")
  save();
else if($_GET["action"] == "add")
  add();

Your js code will look like: 你的js代码看起来像:

function onAdd() {
    $("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
    $.post(
            'classes/Award.php?action=add'
            ).success(function(resp) {
        json = $.parseJSON(resp);
    });
}

function onSave() {
    $("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
    $.post(
            'classes/Award.php?action=save'
            ).success(function(resp) {
        json = $.parseJSON(resp);
    });
}

There is a method that I have discovered. 我发现了一种方法。 Please read my explanation completely to continue. 请完整阅读我的解释继续。 In your ajax code (I think you use jQuery), include another info 'perform', with value = php function name. 在你的ajax代码中(我认为你使用jQuery),包含另一个信息'perform',value = php function name。

$.post("something.php", {
  something1: something1value,
  something2: something2value,
  perform: "php_function_name"
});

Then, in your PHP file, add this piece of code at the beginning : 然后,在PHP文件中,在开头添加这段代码:

<?php if (isset($_POST["perform"])) $_POST["perform"](); ?>

Then, when you call using ajax, you can get a particular function executed. 然后,当您使用ajax调用时,您可以执行特定的功能。 Example Usage : 用法示例:
Javascript : Javascript:

$.post("example.php", {
  name: "anonymous",
  email: "x@gmail.com",
  perform: "register"
}, function(data, status) {
  alert(data);
});

PHP file example.php: PHP文件example.php:

<?php
if (isset($_POST["perform"])) $_POST["perform"]();
function register() {
  echo "Hai " . $_POST["name"] . " ! Your email id is " . $_POST["email"] . ".";
}
?>


When you do this, automatically, function register() will get executed. 执行此操作时,将自动执行函数register()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM