简体   繁体   中英

Is it possible to POST to a class method in Javascript (Ajax -> PHP)?

I'm handling a file-upload with a progress bar using Ajax, and currently I POST to an upload script:

          function uploadFile(revision) 
      {
          var file1 = _("fileToUpload").files[0];

          // FIXME: Developer Option
          alert(file1.name+" | "+file1.size+" | "+file1.type);

          var formdata = new FormData();
          formdata.append("fileToUpload", file1);
          formdata.append("revision", revision);
          var ajax = new XMLHttpRequest();
          ajax.upload.addEventListener("progress", progressHandler, false);
          ajax.addEventListener("load", completeHandler, false);
          ajax.addEventListener("error", errorHandler, false);
          ajax.addEventListener("abort", abortHandler, false);
          ajax.open("POST", "../file_upload_parser.php");
          ajax.send(formdata);    
      }

However, if possible I want to move my upload into a class method (let's say there's a class called FileHandler and I want to be able to POST to it's upload() function.

Would it be possible to POST it to the class's upload method?

Obviously I want to be able to keep the functionality of a loading bar, and if anybody needs to view the source code for the Javascript, here's a link to where I essentially copy-pasta'd code and made a few changes (upload_form.html):

JavaScript File Upload

As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,

<?php
class Car {     
    function getCarType() {
        return "Super Car";
    }
}
?>

Then in your handler file,

<?php
require_once 'Car.php';

if(isset($_POST['getCarType'])) {
     $car = new Car();
     $result = $car->getCarType();
}

echo $result;
?>

You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.

这不是关于javascript的问题,而是关于“如何在PHP中正确路由请求?”尝试查看类似Symfony的Router的内容: https : //symfony.com/doc/current/book/routing.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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