【问题标题】:How to insert knockout generated JSON data in the mySql table?如何在mySql表中插入敲除生成的JSON数据?
【发布时间】:2018-02-24 06:19:06
【问题描述】:

我有一个简单的表单,可以生成'brand name' 输入框的JSON 格式。我使用knockout.js 从表单中生成JSON。现在,如何将此生成的数据提供给php 操作文件,以便使用php 在字段'brand_name' 中的字段'brand_name' 中将这个JSON 数据插入我的mySql 表中?

这是我的表格:

<button data-bind='click: addBrandName'>Add a drug</button>
<form action="php/action.php">
   <table data-bind="foreach: brandNames">
      <tbody >
         <td>
            <label>Brand name</label>
            <input type="text" data-bind='value: brandName'>
         </td>
      </tbody>
   </table>
   <button type="submit">Submit</button>
</form>
<p>
   <button data-bind='click: save, enable: brandNames().length > 0'>Save to JSON</button>
</p>
<div>
   <textarea data-bind='value: lastSavedJson' rows='10' cols='33'> 
   </textarea>
</div>

这是脚本:

<script>
   $( document ).ready(function() {
   var initialData = [
   ];

   var brandNamesModel = function(brandNames) {
   var self = this;
   self.brandNames = ko.observableArray(ko.utils.arrayMap(brandNames, function(drug) {
       return { 
           brandName: drug.brandName };
   }));

   self.addBrandName = function() {
       self.brandNames.push({
           brandName: ""
       });
   };

   self.save = function() {
       self.lastSavedJson(JSON.stringify(ko.toJS(self.brandNames), null, 2));
   };

   self.lastSavedJson = ko.observable("")
   };

   ko.applyBindings(new brandNamesModel(initialData));        
   });
</script>

我正在尝试这个 php 操作,但它肯定不起作用。

$dbCon = mysqli_connect(localhost, $user, $password, $database) 
        or die ("error connecting database");
echo "Connected";

$data = file_get_contents($lastSavedJson);
$arrat = json_decode($data, true);

foreach($array as $row)
{
    $sql = "INSERT INTO b_name(brand_name) VALUES('".$row["brandName"]."')";
    mysqli_query($bdCon, $sql);
};

我正在努力理解它,任何帮助将不胜感激。 如果没有 php,这里就是表单的工作小提琴 - fiddle

【问题讨论】:

    标签: php json mysqli knockout.js


    【解决方案1】:

    请尝试这样的ajax调用

       $.ajax({
            url: "your api url",
            type: "post",
            data: ko.toJSON(self),
            contentType: "application/json",
            success: function(data){
                console.log(data);
                alert("success");
             },
             error:function(jqXHR, textStatus, errorThrown) {
                alert("failure");
             }   
       });  
    

    在您的 php 中,您应该在浏览器控制台上检查以下 php 文件中是否有数据。检查您在控制台中发送的数据。

    print_r($_POST['data']);
    

    【讨论】:

    • 是的,我想将此(或根据输入的任何其他内容)保存在字段“brand_name”中名为“b_names”的表中。
    • 谢谢,但是它返回一个错误:Warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty
    • 您的数据没有出现在您的 php 文件中。你可以为此使用ajax调用吗?如果您说我可以向您发送 ajax 调用如何将数据发送到 json 中的 php。
    • 如果您能指导我如何将这些 json 数据从表单获取到表单上下文中的 php 文件,那将非常有帮助。
    • 在您的 php 中不发出您从表单发送的数据您的文件没有在 php 中出现请首先检查您的呼叫,如果数据来了,然后尝试您没有从 knockout.js 正确发送数据。我发现你的 php 中的一个错误是 $arrat 它应该是 $array foreach 循环
    【解决方案2】:

    我从Wern Ancheta 的博客中得到了最好的帮助。这是一篇很棒的文章,他解释了那里的所有代码。

    这是他如何完成我一直在寻找的工作的版本:

    htmlknockout 代码:

    <div class="container" data-bind="load: loadData()">
        <div class="new_student">
            <input type="text" class="name" placeholder="name" data-bind="value: person_name, hasfocus: person_name_focus"/>
            <input type="text" class="age" placeholder="age" data-bind="value: person_age"/>
    
            <button data-bind="click: createPerson">Create</button>     
        </div>
    
        <table data-bind="visible: people().length > 0" class="students">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Remove</th>
                    <th>Update</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: people">
                <tr>
                    <td>
                        <span data-bind="text: name, click: nameUpdating, visible: !nameUpdate()"></span>
                        <input type="text" class="name" data-bind="value: name, visible: nameUpdate, hasfocus: nameUpdate">
                    </td>
                    <td>
                        <span data-bind="text: age, click: ageUpdating, visible: !ageUpdate()"></span>
                        <input type="text" class="age" data-bind="value: age, visible: ageUpdate, hasfocus: ageUpdate">
                    </td>
                    <td><a href="#" data-bind="click: $root.removePerson">remove</a></td>
                    <td><a href="#" data-bind="click: $root.updatePerson">update</a></td>
                </tr>
            </tbody>
        </table>    
    
        <button data-bind="click: echoPerson">echo</button>
    </div>
    
    
    
    
    <script>
    var personModel = function(id, name, age){
        var self = this;
        this.id = ko.observable(id);
        this.name = ko.observable(name);
        this.age = ko.observable(age);
    
        this.nameUpdate = ko.observable(false);
        this.ageUpdate = ko.observable(false);
    
        this.nameUpdating = function(){
            self.nameUpdate(true);
        };
        this.ageUpdating = function(){
            self.ageUpdate(true);
        };
    
    };
    
    var model = function(){
    
        var self = this;
        this.person_name = ko.observable("");
        this.person_age = ko.observable("");
        this.people = ko.observableArray([]);
        this.person_name_focus = ko.observable(true);
    
        this.createPerson = function(){
            if(self.validatePerson()){
    
                var person = {'name' : this.person_name(), 'age' : this.person_age()};
    
                $.ajax(
                    {
                        url: 'refresher_save.php',
                        type: 'POST',
                        data: {'student' : person, 'action' : 'insert'},
                        success: function(id){
                            console.log(this);
                            self.people.push(new personModel(id, self.person_name(), self.person_age()));
                            self.person_name("");
                            self.person_age("");
                        }
                    }
                );          
    
            }else{
                alert("Name and age are required and age should be a number!");
            }
        };
    
        this.validatePerson = function(){
            if(self.person_name() !== "" && self.person_age() != "" && Number(self.person_age()) + 0 == self.person_age()){
                return true;
            }
            return false;
        };
    
        this.removePerson = function(person){
    
            $.post(
                'refresher_save.php', 
                {'action' : 'delete', 'student_id' : person.id()}, 
                function(response){
    
                    self.people.remove(person);
                }
            );
        };
    
    
        this.updatePerson = function(person){
            var id = person.id();
            var name = person.name();
            var age = person.age();
    
            var student = {'id' : id, 'name' : name, 'age' : age};
            $.post(
                'refresher_save.php', 
                {'action' : 'update', 'student' : student}
    
            );
        };
    
        this.loadData = function(){
            //fetch existing data from database
    
            $.ajax({
                url : 'refresher_save.php',
                dataType: 'json',
                success: function(data){
    
    
                    for(var x in data){
                        var id = data[x]['id']
                        var name = data[x]['name'];
                        var age = data[x]['age'];
                        self.people.push(new personModel(id, name, age));
                    }
    
                }
            });
            /*
            note: nothing would actually show up in the success function if the
            data that was returned from the server isn't a json string
            */
        };
    
    
        this.echoPerson = function(){
            console.log(ko.toJS(self.people()));
        };
    
    };
    
    ko.applyBindings(new model());
    </script>
    

    服务器端phpconnectinsertupdatedelete数据为:

    <?php
    $db = new MySqli('localhost', 'ashonko', '', 'tutorials');
    
    $action = (!empty($_POST['action'])) ? $_POST['action'] : '';
    $student = (!empty($_POST['student'])) ? $_POST['student'] : '';
    
    
    if(!empty($student)){
        $name = $student['name'];
        $age = $student['age']; 
    }
    
    switch($action){
    
        case 'insert':
    
            $db->query("INSERT INTO students SET name = '$name', age = '$age'"); 
            echo $db->insert_id; //last insert id
        break;
    
        case 'update':
    
            $id = $student['id'];
            $db->query("UPDATE students SET name = '$name', age = '$age' WHERE id = '$id'");
        break;
    
        case 'delete':
    
            $id = $_POST['student_id'];
            $db->query("UPDATE students SET status = 0 WHERE id = '$id'");
        break;
    
        default:
            $students = $db->query("SELECT * FROM students WHERE status = 1");
            $students_r = array();
            while($row = $students->fetch_array()){
    
                $id = $row['id'];
                $name = $row['name'];
                $age = $row['age'];
                $name_update = false;
                $age_update = false;
                $name_focus = false;
                $age_focus = false;
    
                $students_r[] = array(
                    'id' => $id, 'name' => $name, 'age' => $age, 
                    'nameUpdate' => $name_update, 'ageUpdate' => $age_update,
                    'nameHasFocus' => $name_focus, 'ageHasFocus' => $age_focus
                    ); 
            }
    
            echo json_encode($students_r);
        break;
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 2015-01-09
      • 2017-02-13
      • 1970-01-01
      • 2019-11-30
      • 2020-03-15
      • 2019-09-12
      • 1970-01-01
      • 2018-03-01
      相关资源
      最近更新 更多