簡體   English   中英

來自單獨JavaScript文件的PHP文件中的調用方法

[英]Calling method in PHP file from separate JavaScript file

我有一個javascript文件,試圖從該javascript文件進行ajax調用以執行其他php文件的方法。

Javascript文件-a.js

function update() {
        $.ajax({
            url:"abcd.php",
            type: "POST",
            dataType: 'json',
            data: {"updateMethod()"}

            success:function(result){
                console.log(result);
            }
         });
}

PHP文件-abcd.php

<?php

class abcd {
    public function updateMethod() {
        //execute this part of the code
    }

    public function insertMethod() {

    }

    public function deleteMethod() {

    }


}

我無法調用PHP方法。 我的AJAX查詢出了什么問題,或者我需要在PHP文件端做些什么來調用該方法。

我不知道您要嘗試做什么,但是您可以這樣進行:

function update() {
    $.ajax({
        url:"abcd.php",
        type: "POST",
        dataType: 'json',
        data: {methodName: "updateMethod"},
        success:function(result){
            console.log(result);
        }
     });
}

在服務器端:

<?php

class abcd {
    public function updateMethod() {
        //execute this part of the code
    }

    public function insertMethod() {

    }

    public function deleteMethod() {

    }
}

$abcd = new abcd();
$method = $_POST['methodName'];
$result = $abcd->$method();

刪除此行

dataType: 'json',

並發送沒有json的數據

如果您在php中發送json必須是:

$data = file_get_contents('php://input');

PHP“ php:// input”與$ _POST

或者更好的jQuery:

var methodName = "YourMethodName";
var y = "Cymbal";

$.post( "test.php", { methodName: methodName, lastname: y })
  .done(function( data ) {
   alert( "Data Loaded: " + data );
});

也許像這樣更安全,我認為您還需要CRUD操作的函數參數(未經測試):

后端:

class CRUD
{
    public function update($args) 
    {
       $input = $args['exampleInput'];
       // sanitize input 
       // prepared query
       // $stmt->execute($input);
    }
}


function access($class, $method, $args) 
{
    if (method_exists($class, $method)) {
        return call_user_func_array([$class, $method], [$args]);
    } 
}

$data = file_get_contents('php://input');
access('CRUD', $data->method, json_decode($data->args));

JS:

function handleAction(methodName, arguments) {
  $.ajax({
    url: "crudFile.php";
    type: "POST",
    data: { method: methodName, args: arguments },
    dataType: 'json',
    success: function (result) {
      console.log(result);
    }
  });
}

var inputs = {
  exampleInput: function () {
    return document.getElementById('your-div-id').textContent();
  },
};

// usage

handleAction('update', inputs);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM