【问题标题】:How to get a variable from PHP file using Ajax?如何使用 Ajax 从 PHP 文件中获取变量?
【发布时间】:2020-07-07 06:49:09
【问题描述】:

我刚开始学习 PHP 和 Ajax,但我不知道如何使用 Ajax 将单个变量从 PHP 文件带入我的 html 文件。你能解释一下它是如何工作的吗?

到目前为止,我了解到您创建了请求:

var xhttp = new XMLHttpRequest();

然后将其发送到服务器:

xhttp.open("GET", "demo_get.php", true);
xhttp.send();

然后你从 PHP 文件中获取数据使用

xhttp.responseText

现在,我只想从服务器发送一个变量,例如

$name = "John"

为了只发送那个特定的变量,我的 php 代码应该是什么样子?

【问题讨论】:

    标签: php ajax


    【解决方案1】:

    作为初学者,使用 jQuery 处理 AJAX 请求会容易得多。我已经在这个行业工作了大半辈子,而且我仍然经常使用它。

    getstuff.php

    header('Content-type: application/json');
    echo json_encode(["FirstName" => "John"]);
    exit;
    

    jquery:

    $.ajax({
        url: '/getstuff.php',
        success: function (response) {
            console.log(response);
            alert(response.FirstName);
        }
    });
    

    【讨论】:

    • PHP 的 header() 函数必须这样调用:header('Content-Type: application/json');
    【解决方案2】:

    我建议使用 JSON 作为数据交换格式,这里是 javascript 部分:

    let request = new XMLHttpRequest();
    
    request.open('GET', 'demo_get.php', true);
    
    request.onload = function() {
        if (this.status >= 200 && this.status < 400) {
            // Success
            let parsed_response = JSON.parse(this.response.trim());
            console.log(parsed_response.my_var);
        } else {
            // Error
            console.log(this.response);
        }
    };
    request.onerror = function() {
        console.log('Connection error!');
    };
    request.send();
    

    PHP 部分将如下所示:

    <?php
    header('Content-Type: application/json');
    $my_response_data = ['my_var' => 'foo'];   
    echo json_encode($my_response_data);
    exit;
    

    ... 以及一些关于 XMLHttpRequest.responseText 与 XMLHttpRequest.response 的useful info

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多