如何引用与PHP一起使用的JSON并将Survey.js存储在mysql中

时间:2018-10-24 03:01:14

标签: php json surveyjs

我的php文件的代码如下所示

<?php

    $connect = mysqli_connect("localhost","root","","surveytest");
    $query = '';
    $table_data = '';
    $filename2 = "employee_data.js";
    $data2 = file_get_contents($filename2);
    $array2 = json_decode($data2, true);


     foreach($array2 as $row) //Extract the Array Values by using Foreach Loop
              {
               $query .= "INSERT INTO survey(name, gender, designation) 
               VALUES 
               ('".$row["name"]."', 
               '".$row["gender"]."', 
               '".$row["designation"]."'); ";  // Make Multiple Insert Query 

               $table_data .= '
                <tr>
           <td>'.$row["name"].'</td>
           <td>'.$row["gender"].'</td>
           <td>'.$row["designation"].'</td>
          </tr>
               '; //Data for display on Web page
              }
              if(mysqli_multi_query($connect, $query)) //Run Mutliple Insert Query
        {
         echo '<h3>Imported JSON Data</h3><br />';
         echo '
          <table class="table table-bordered">
            <tr>
             <th width="45%">Name</th>
             <th width="10%">Gender</th>
             <th width="45%">Designation</th>
            </tr>
         ';
         echo $table_data;  
         echo '</table>';
              }  
    ?>

我的javascript文件的代码如下:

var json =
 {  
  "items": [
    {  
     "name": "Rusydi",  
     "gender": "Male",  
     "designation": "System Architect"  
    },  

    {  
     "name": "Hakim",  
     "gender": "Male",  
     "designation": "Conservation worker"  
    }
 ]
 }

嘿!我是javascript和JSON的初学者。
我尝试将var json添加到mysql数据库中。
现在我想引用此javascript文件(var json),但是它不起作用。

我的目的是尝试将此变量存储在mysql中。
这就是为什么我尝试这样做的原因。

var json = {
    questions: [
        {
            name: "name",
            type: "text",
            title: "Please enter your name:",
            placeHolder: "Jon Snow",
            isRequired: true
        }, {
            name: "birthdate",
            type: "text",
            inputType: "date",
            title: "Your birthdate:",
            isRequired: true
        }, {
            name: "color",
            type: "text",
            inputType: "color",
            title: "Your favorite color:"
        }, {
            name: "email",
            type: "text",
            inputType: "email",
            title: "Your e-mail:",
            placeHolder: "jon.snow@nightwatch.org",
            isRequired: true,
            validators: [
                {
                    type: "email"
                }
            ]
        }
    ]
};

这是完整代码。 https://surveyjs.io/Examples/Library/?id=questiontype-text&platform=jQuery&theme=default

Survey
    .StylesManager
    .applyTheme("default");

var json = {
    questions: [
        {
            name: "name",
            type: "text",
            title: "Please enter your name:",
            placeHolder: "Jon Snow",
            isRequired: true
        }, {
            name: "birthdate",
            type: "text",
            inputType: "date",
            title: "Your birthdate:",
            isRequired: true
        }, {
            name: "color",
            type: "text",
            inputType: "color",
            title: "Your favorite color:"
        }, {
            name: "email",
            type: "text",
            inputType: "email",
            title: "Your e-mail:",
            placeHolder: "jon.snow@nightwatch.org",
            isRequired: true,
            validators: [
                {
                    type: "email"
                }
            ]
        }
    ]
};

window.survey = new Survey.Model(json);

survey
    .onComplete
    .add(function (result) {
        document
            .querySelector('#surveyResult')
            .innerHTML = "result: " + JSON.stringify(result.data);
    });

$("#surveyElement").Survey({model: survey});

或者我该怎么办?

3 个答案:

答案 0 :(得分:0)

从文件中删除“ var json =“,并将扩展名更改为“ .json”,而不是“ .js”。

由于您的JavaScript文件不包含有效的JSON字符串,因此php无法对其进行解码。

employee_data.json

 {  
  "items": [
    {  
     "name": "Rusydi",  
     "gender": "Male",  
     "designation": "System Architect"  
    },  

    {  
     "name": "Hakim",  
     "gender": "Male",  
     "designation": "Conservation worker"  
    }
  ]
 }

答案 1 :(得分:0)

好吧,我看到的是这样的:

//employee_data.js
var json =
{

然后您导入

$filename2 = "employee_data.js";
$data2 = file_get_contents($filename2);
$array2 = json_decode($data2, true);

JSON并不是JavaScript代码(严格来说),它是将JavaScript对象格式化或编码为字符串的方式。 ( J ava S 密码 O 否决 N )。因此,您的文件应以{开头,而不是变量设置。因此,您只需要删除该var json =位即可。

如果您选中var_dump($array2);,它可能会说NULL,如果您在进行echo json_last_error_msg()之后立即选中json_decode,它可能会说类似Syntax error invalid JSON等。

可以这样复制:

 var_dump(json_decode('var json={"foo":"bar"}', true)); 
 echo json_last_error_msg();

输出:

NULL
Syntax error

Sandbox

如果从我过于简单的示例中删除var json =,则会得到以下信息:

array(1) {
   ["foo"]=> string(3) "bar"
}
No error

干杯!

答案 2 :(得分:0)

首先,隔离紧随var json =并以}结尾的json数据,其后紧跟;

然后通过将所有键都用双引号引起来修复json字符串。

最后,将数据转换为数组,以便您可以使用questions子数组执行查询过程。

*请注意,我不建议您使用mysqli_multi_query(),因为它不稳定/不安全。我建议您使用准备好的语句来插入数据。我将避免解释此任务,因为在StackOverflow上有许多执行此操作的示例。

代码:(PHP Demo)(Regex 1 Demo)(Regex 2 Demo

if (preg_match('~^var json = \K{.*?}(?=;)~ms', $js_file_contents, $match)) {  // cut away extra
    $json = preg_replace('~^\s*\K\w+~m', '"\0"', $match[0]);  // quote-wrap the keys
    var_export(json_decode($json, true));  // convert json string to array and display
}

输出:

array (
  'questions' => 
  array (
    0 => 
    array (
      'name' => 'name',
      'type' => 'text',
      'title' => 'Please enter your name:',
      'placeHolder' => 'Jon Snow',
      'isRequired' => true,
    ),
    1 => 
    array (
      'name' => 'birthdate',
      'type' => 'text',
      'inputType' => 'date',
      'title' => 'Your birthdate:',
      'isRequired' => true,
    ),
    2 => 
    array (
      'name' => 'color',
      'type' => 'text',
      'inputType' => 'color',
      'title' => 'Your favorite color:',
    ),
    3 => 
    array (
      'name' => 'email',
      'type' => 'text',
      'inputType' => 'email',
      'title' => 'Your e-mail:',
      'placeHolder' => 'jon.snow@nightwatch.org',
      'isRequired' => true,
      'validators' => 
      array (
        0 => 
        array (
          'type' => 'email',
        ),
      ),
    ),
  ),
)