【问题标题】:php how to return JSON for jQuery .get() or .post() request, parse it and output to browserphp 如何为 jQuery .get() 或 .post() 请求返回 JSON,解析它并输出到浏览器
【发布时间】:2020-11-09 05:50:00
【问题描述】:

编辑: 我现在可以输出表格,但奇怪的是,尝试使用 JS 或 jQuery 方法解析从 PHP 返回的 JSON 会导致在调试器中跳过所有剩余的行,而对浏览器的输出为零。在哪里不解析并使用它来构建表工作。 此外,尝试使用解析方法 .append() JSON 或不使用 ` 不起作用。
我现在很困惑。

无论如何,工作的 jQuery 看起来像这样发出 .post() 请求,请注意我添加了 'json' 第四个参数,尽管没有它它可能会工作。

$(document).ready(function(){
    $('#disease_btn').click(function(){
        showDisease();
    });
});

function showDisease(){
    //var disease = $("#disease-dropdown:selected").text();
    //var disease = $("#disease-dropdown:selected").val();
    var disease_dropdown = document.getElementById("disease-dropdown")
    var disease = disease_dropdown.options[disease_dropdown.selectedIndex].text;
    var controller = 'controller.php';
    $.post(controller, //url, data, callback, dataype=Json
    {
    page: 'SpaPage',
    command: 'search-disease',
    search_term: disease
    },
    function(disease_json, status){
        //#search-results display table
        //var disease_obj = JSON.parse(disease_json); this did not work
        //var disease_obj = jQuery.parseJSON(disease_json);  //this did not work
        var disease_obj = disease_json;
        //$('#test-out').append(disease_obj);  /this did not work
        var table = $.makeTable(disease_obj);
        $('#search-results').append(table);  //this worked!
    }, 'json');

    //https://stackoverflow.com/a/27814032/13865853
    $.makeTable = function(disease_obj){
        var table = $('<table border=1>');
        var tblHeader = "<tr>";
        for (var h in disease_obj[0]) tblHeader += "<th>" + h + "</th>";
        $(tblHeader).appendTo(table);
        $.each(disease_obj, function(index, value){
        var tblRows = "<tr>";
        $.each(value, function (key, val){
        tblRows += "<td>" + val + "</td>";
        });
        tblRows += "</tr>";
        $(table).append(tblRows);
    });
    return ($(table));
    }
};

我模仿了我在这里看到的那个表格代码:https://stackoverflow.com/a/27814032/13865853 我有点明白,但仍然不是很清楚。我猜它正在输出 HTML,所以我可以为表格添加一个类以利用引导程序。

在 PHP 方面我这样做:

case 'search-disease':
            $matches_arr = [];
            $disease = $_POST['search_term'];
            $matches_arr = search_disease($disease);
            //todo: decide to use session or returned arr
            if(isset($_SESSION['disease-matches_arr'])){
                $matches_arr = $_SESSION['disease-matches_arr'];
            }
            if(count($matches_arr) > 0) {
                //jsonify array here to send back
                //https://stackoverflow.com/a/7064478/13865853
                //https://stackoverflow.com/a/58133952/13865853

                header('Content-Type: application/json');
                $disease_json = json_encode($matches_arr);
                echo $disease_json;
                exit;
            }

然后model.php 与数据库的交互如下所示:

function search_disease($disease_option){
    // search DB for substring of question
    //add results to an array of strings
    //return array of strings or empty array
    //
    $user_id = -1;
    $matches_arr = array();
    $sql = "SELECT * FROM diseases 
    WHERE disease LIKE '%$disease_option%'";

    $result = mysqli_query(Db::$conn, $sql);
    if (mysqli_num_rows($result) > 0) {
        //iterate
        while($row = mysqli_fetch_assoc($result)){
            //get username
            $disease = $row['disease'];
            $food = $row['food'];
            $en_name = $row['en_name'];
            $health_effect = $row['healthEffect'];
            $metabollite = $row['metabollite'];
            $citation = $row['citation'];
            $next_row = array("Disease"=>$disease, "Food"=>$food,
                "Name"=>$en_name, "Health Benefits"=>$health_effect, "Metabollite"=>$metabollite,
                "Sources"=>$citation);
            $matches_arr[] = $next_row;
        }
    }
    $_SESSION['disease-matches_arr'] = $matches_arr;
    return $matches_arr;
    //https://stackoverflow.com/questions/1548159/php-how-to-sen

所以我设置了一个会话变量并返回它,仍然需要决定哪种方式,但它们都在工作。

我的问题还有:

  1. 为什么解析方法会导致这种奇怪的行为?
  2. 如何将 JSON 输出到测试 &lt;div&gt;

【问题讨论】:

标签: php jquery json ajax


【解决方案1】:

如果您必须将数据从PHP 返回到javascript,如果数据类型是数组,则必须使用json_encode(),否则只需返回。 要通过 javascript 对数组类型数据采取行动,您必须通过 JSON.parse() 函数解码此 json 数据。

Array例子

 $data = array('carname' => 'TOYOTA','model'=>'ARTYIR500');
 echo json_encode($data);
 exit;

String 例子

 echo 'lorem ipsum is a simple text';
 exit;

【讨论】:

  • if data type is array 如果说像if data type is an array or object (not a simple type such as string, int or bool) 这样的话会更准确。对象也需要编码,而不仅仅是数组。
  • To take action with array type data by javascript you have to decode this json data by JSON.parse() function...不一定。例如,可以通过设置dataType: "json" 选项告诉 jQuery 的 ajax 函数自动解析。如果使用fetch(),您将使用response.json()。有几种不同的方式,所以你的说法太简单了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 2018-11-02
  • 1970-01-01
  • 2017-09-25
  • 2013-08-27
相关资源
最近更新 更多