使用AJAX在Javascript中调用PHP函数

ove*_*ing 3 javascript php ajax

我有一个javascript文件,我想在php服务器端调用一个函数,并使用ajax将结果返回给客户端,但我不知道如何向特定的php函数发出请求.

这是我的文件:

javascript文件基本上从html表单中检索用户名,我想将该用户名发送到php并检查数据库是否可用.

something.js:

function check_availability()
{
    var username = $.trim(document.getElementById('usernameField').value);
    var xmlhttp= new XMLHttpRequest();

    // not sure how to make the request here to check_availability() under php
}
Run Code Online (Sandbox Code Playgroud)

PHP文件将只检查从js文件传递给数据库的用户名,如果它的可用返回true,否则为false.

something.php:

    class Something_Model {
    private $data;
    private $table;

    public function __construct() {
        $this->data = new udata(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
    }

    # check for username availability
    public function check_availability()
    {
        // make the check here, but needs to retrieve username from js file
        echo "here";
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,在Something_Model类中,我想从javascript调用check_availability(),有人能给我一个例子来进行这个ajax调用吗?另外,如何将结果返回给javascript?我需要将其编码为JSON obj吗?

非常感谢.

Fen*_*ton 5

您无法直接在PHP中调用函数 - 但您可以调用PHP页面,而PHP页面又可以调用PHP函数.例如...

service.php

include_once('something.php');
$model = new Something_Model();
$model->check_availability();
Run Code Online (Sandbox Code Playgroud)

something.js

function check_availability() {

    var request = new XMLHttpRequest();
    request.open('GET', 'http://yoursite/service.php', false);
    request.send();

    if (request.status === 200) {
      alert(request.responseText);
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用了一个非常简单的XMLHttpRequest示例 - 这个示例在请求发生时实际阻塞.实际上,您可能希望使用回调并允许它以异步方式运行,但我希望尽可能缩短答案.