【问题标题】:AJAX connect to PHP OOP WebServiceAJAX 连接到 PHP OOP WebService
【发布时间】:2014-04-14 19:27:56
【问题描述】:

为什么这不起作用?

class WebService {
    public static function CheckUserLogin() {
    }
}

如何调用这个函数?

我的 login.php 表单

<form id="form" name="form" method="POST" onsubmit="" action="">

E-Mail: <input type="text" size="30" name="email" id="email" >
Passwort: <input type="text" size="30" name="passwort" id="passwort" >

<input type="submit" value="Login" name="submit" />

</form>

login.js

 $(function () {
    $('form').on('submit', function (e) {
        var email = document.getElementById('email').value;
        var passwort = document.getElementById('passwort').value;

        $.ajax({
            type: "POST",
            url: "WebService.php",
            data: "{ 'email': '" + email + "', passwort: '" + passwort + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response);
            },
            failure: function (response) {
                alert(response);
            }
        });
      e.preventDefault();
    });
  });

我想调用函数 CheckUserLogin()。我怎么能这样做?或者我必须做什么?

非常感谢!

【问题讨论】:

  • 您的 PHP 文件实际上命名为 WebService.php 吗?你也在使用某种框架吗?
  • CheckUserLogin 需要返回 JSON 响应 - 目前它不返回任何内容。然后,根据下面的答案,您可以echo json_encode() 该函数的结果生成一个名为“WebService.php”的文件。
  • 另外,养成在浏览器中使用网络监视器实时观看 AJAX 请求的习惯。这将极大地帮助您了解它们是如何工作的,以及为什么特定案例不起作用。

标签: javascript php jquery ajax call


【解决方案1】:

在您的 ajax 调用中,您可以连同 url 一起发送一个参数,say-action:

....
url: "WebService.php?action=checkLogin",
....

然后在PHP中,只需获取这个变量并调用所需的函数-

if(isset($_GET['type'])){
   if($_GET['type'] == "checkLogin"){
      $ws = new WebService;
      echo $ws->CheckUserLogin(); 
      // this will call the desired function and the result will be obtained by the ajax
   }
}

同样你可以使用相同的概念在不同的点调用不同的函数。

【讨论】:

    【解决方案2】:

    您需要实例化类 WebService。对文件的调用只是按程序运行文件。

    $webservice = new WebService;
    $webservice->CheckUserLogin();
    

    【讨论】:

      【解决方案3】:

      你必须像这样检查 webservice.php 中的 POST 数据

      if(isset($_POST['email'],$_POST['passport'])){}
      

      如果条件为真,则调用您的方法

      $a = new WebService;
      $a->CheckUserLogin();
      

      成功了!)

      【讨论】:

        猜你喜欢
        • 2014-11-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-24
        • 1970-01-01
        • 1970-01-01
        • 2014-01-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多