简体   繁体   English

从html获取php生成的json

[英]Getting php-generated json from html

I have a form in an html file which sends data to a php file. 我在html文件中有一个表单,可将​​数据发送到php文件。 That php file selects from the database, transforms the results into a json file and sends it back to the html file. 该php文件从数据库中选择,将结果转换为json文件,然后将其发送回html文件。

I would like to know how can I get the json from the php; 我想知道如何从php获取json; I do get the reply (from the network tab in the inspection menu), but I don't know how to get it (to echo/alert/make a chart with it). 我确实收到了答复(从“检查”菜单中的“网络”选项卡中),但是我不知道如何获得答复(用它来回显/提醒/制作图表)。 Thanks in advance! 提前致谢!

This is my code to send the data: 这是我发送数据的代码:

<script type="text/javascript">
    $( function() {
        $( ".datepicker" ).datepicker({
            minDate: new Date(2015, 8 - 1, 25),
            maxDate: "0"
        });
    });

$(function () {
    // On form's submit, takes both input's values...
    $('form').on('submit', function (e) {
        var from = $("#from").val();
        var to = $("#to").val();
        // ...to compare them and displays an error if "to" is smaller than "from"
        if(Date.parse(from) > Date.parse(to)){
            alert("Invalid Date Range");
        }
        else{
            e.preventDefault();
            $.ajax({
                type: 'post',
                url: 'classes/Select.php',
                data: $('form').serialize(),
                success: function () {
                    alert('data sent');
                }
            });
        }
    });
});
</script>

And this is the php part that makes the json (left out all the mysql part and such): 这是制作json的php部分(省略了所有mysql部分,等等):

while ($arr = $query->fetch(PDO::FETCH_ASSOC)) {
    echo json_encode($arr);

In your javascript ajax call code, you probably have a success: key. 在您的javascript ajax调用代码中,您可能成功了:键。 Try: 尝试:

success: function(data) { console.log(data); }

if you get a JSON string use json_decode($json) and you get the value you want: 如果获得JSON字符串,请使用json_decode($ json)并获得所需的值:

$json = '{"key-example": 12345}';

$obj = json_decode($json);
print $obj->{'key-example'}; // 12345

Since you are using a loop in your php, create an array that will hold the results, when the loop finishes echo the results with json_encode ; 由于您在php中使用循环,因此请创建一个将保存结果的数组,当循环结束时,请使用json_encode回显结果;

$results = [];
while ($arr = $query->fetch(PDO::FETCH_ASSOC)) {
    $results[] = $arr;
}
echo json_encode($results);

Then in your javascript 然后在你的JavaScript

    $.ajax({
       type: 'post',
       url: 'classes/Select.php',
       data: $('form').serialize(),
       success: function(data) {
           var results = JSON.parse(data); // convert the results to json
           console.log(results);
       }
   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM