dongpao2871 2019-05-06 18:46
浏览 43
已采纳

试图用php中的按钮发布json内容

I'm trying to post new data into my json file by using jquery by entering the values of the input but nothing happens when I do. I apologize in advance for this slightly dumb question and I'm very grateful for any help!

I'm very new to programming but I have no clue if this is even possible to do. Below is my 'index.php' file where my jquery and button is to add new data.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
    <input type="text" id="name">
    <input type="text" id="grade">
    <button id="btn">Add</button>
</body>

<script>
$(document).ready(function(){
    $.getJSON('http://localhost/mytest/json.php', function(data) {

        for (i=0; i < data.length; i++) {
            if (data[i].grade < 5) {

                document.write("<p style='color: red;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
            } else {

                document.write("<p style='color: green;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
            }
        }
    });

    // posting the orders



    $('#button').on('click', function() {

        var order = {
            name: $('#name').val(),
            grade: $('#grade').val(),
        }

        $.ajax({
            type: 'POST',
            url: 'http://localhost/mytest/json.php',
            data: order,
            success: function(newStudent) {

            }
        })
    });

});

</script>

</html>

Here below is the JSON file I created with PHP (json.php):

<?php

$student1 = array(
    "name"=>"ali",
    "grade"=>"7"
);

$student2 = array(
    "name"=>"John",
    "grade"=>"4"
);

$student3 = array(
    "name"=>"Martha",
    "grade"=>"2"
);

$student4 = array(
    "name"=>"Jullie",
    "grade"=>"8"
);

$student5 = array(
    "name"=>"Morgan",
    "grade"=>"4"
);


$students = array($student1, $student2, $student3, $student4, $student5);

$j = json_encode($students); // we 'encode' the array into a JSON format
echo $j;

?>
  • 写回答

2条回答 默认 最新

  • du5739 2019-05-06 20:17
    关注

    Hello this is a fixed version of your code

    1. Persisten data
    2. Remove dumplicate code for pass grade
    3. Create a div with students data(json content)

    index.php

    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    </head>
    <body>
    Name: <input type="text" id="name"><br>
    Grade: <input type="text" id="grade"><br>
    <button id="button">Add</button>
    <div id="students">
    
    </div>
    </body>
    
    <script>
        $(document).ready(function () {
            // fill students div content with document ready
            updateStudents();
    
            $('#button').on('click', function () {
    
                var order = {
                    name: $('#name').val(),
                    grade: $('#grade').val(),
                }
                $.ajax({
                    type: 'POST',
                    url: 'json.php',
                    data: order,
                    success: function (newStudent) {
                        console.log("Success");
                        $("#students").append(setStudents($('#name').val(), $('#grade').val()));
    
                    }
                })
            });
    
            function updateStudents() {
                $.getJSON('students.json', function (data) {
    
                    for (i = 0; i < data.length; i++) {
                        $("#students").append(setStudents(data[i].name, data[i].grade));
    
                    }
                });
            }
    
            function setStudents(name, grade) {
                var color = 'green';
                if (grade < 5) {
                    color = 'red';
                }
                return "<p style='color: " + color + ";'>Name: " + name + "<br>Grade: " + grade + "</p>"
            }
    
        });
    
    </script>
    
    </html>
    

    json.php

    <?php
    
    $file = "students.json";
    
    $content = file_get_contents($file); 
    
    if ($content == null) {
        $data[] = $_POST;
        $jsonData = json_encode($data);
        file_put_contents($file, $jsonData);
    } else {
        $data = $_POST;
        $tempArray = (array) json_decode($content);
        array_push($tempArray, $data);
        $jsonData = json_encode($tempArray);
        file_put_contents($file, $jsonData);
    
    }
    echo $jsonData;
    

    students.json Note: the file could be empty this is just some data

    [{"name":"Pedro","grade":"10"},{"name":"Juan","grade":"10"},{"name":"Lopez","grade":"10"},{"name":"Maria","grade":"5"},{"name":"Miguel","grade":"5"},{"name":"Juana","grade":"4"},{"name":"hugo","grade":"8"},{"name":"Nano","grade":"2"}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题