首页 > 解决方案 > 从 XMLHttpRequest 返回多个数据/响应文本

问题描述

我有一个 js 函数,它调用 xml 请求以从单独的 php 文件中获取数据。我可以通过echoing它从单独的 php 文件中获取返回的数据。

这是我当前的代码:

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function()
    {
        if(this.readyState == 4 && this.status == 200)
        {
            //On Data Receive
            countryHeader.innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "country.php?c=" + countryName, true);
    xhttp.send();

在我的 php 上:

    include("conn.php");

    $c = htmlentities($_GET["c"]);
    $sec_country = mysqli_real_escape_string($con, $c);

    //Searches the db
    $sql = "SELECT * FROM countries WHERE country_code = '$sec_country' LIMIT 1";
    $result = mysqli_query($con, $sql);
    $count = mysqli_num_rows($result);

    if($count == 1)
    {
        //Get Data
        $row = mysqli_fetch_assoc($result);
        $countryName = $row['country_name'];
        $countryPrice = $row['country_price'];
        echo $countryName." is worth $".$countryPrice;
    }
    else
    {
        //Invalid Code/No Data
        echo "No Country Found";
    }

如果我发送一个国家代码,例如rus,它将Russia is worth $1B主要从 返回echo $countryName." is worth $".$countryPrice; 但是如果我想单独发送$countryName$countryPrice

例如responseText.aresponseText.b

标签: javascriptphp

解决方案


您可以从 PHP 发送 JSON 响应。这是一个参考-> https://www.w3schools.com/js/js_json_php.asp


推荐阅读