Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 表单获取变量并发布到php数组_Javascript_Php_Json - Fatal编程技术网

Javascript 表单获取变量并发布到php数组

Javascript 表单获取变量并发布到php数组,javascript,php,json,Javascript,Php,Json,我希望获取表单变量,并将它们推入内存中的数组中,而不是通过重新加载来破坏页面。这确实是我不擅长的事情。这能做到吗?我需要使用基于表单的php向json文件添加内容 JSON数据: var members = [ { "Class": "B", "Rating": "1776", "ID": "12537964", "Name": "Ahmed, Jamshed", "Expires": "2018.10.18" }, { "Class": "C", "Rating": "1500", "ID

我希望获取表单变量,并将它们推入内存中的数组中,而不是通过重新加载来破坏页面。这确实是我不擅长的事情。这能做到吗?我需要使用基于表单的php向json文件添加内容

JSON数据:

var members = [ 
{ "Class": "B", "Rating": "1776", "ID": "12537964", "Name": "Ahmed, Jamshed", "Expires": "2018.10.18" }, 
{ "Class": "C", "Rating": "1500", "ID": "12210580", "Name": "Attaya, James", "Expires": "2019.01.12" }, 
{ "Class": "F", "Rating": "0000", "ID": "16281977", "Name": "Auld, Thomas", "Expires": "" }, 
{ "Class": "B", "Rating": "1759", "ID": "10117780", "Name": "Badamo, Anthony", "Expires": "2018.09.12" }
]
JS:


姓氏:
成员:
评级: 身份证件: 类别: 添加新玩家 重置表单 函数validateForm(){ var memName=document.getElementById('mem-name').value; var memExpires=document.getElementById('mem-expires')。值; var memRating=document.getElementById('mem-rating')。值; var memID=document.getElementById('mem-ID')。值; var memClass=document.getElementById('mem-class').value; 如果(memName==“”){ 警告(“必须填写姓名”); 返回false; }否则{ $.ajax({ 键入:“GET”, url:'welcome.php', 数据:{ “mem name”:memName, “mem expires”:memExpires, “记忆评级”:记忆评级, “mem ID”:memID, “mem类”:memClass }, 成功:函数(数据){ log('我的数据应该在这里:'+数据); members=JSON.parse(数据); 控制台日志(成员); } }); } }
MEMBERS.PHP:

<?php 

// Clean up data 
function test_input($data) { 
$data = trim($data); 
$data = stripslashes($data); 
$data = htmlspecialchars($data); 
return $data; 
} 


// define variables and set to empty values 
$mem_name = $mem_expires = $mem_rating = $mem_ID = $mem_class = ""; 

if ($_SERVER["REQUEST_METHOD"] == "GET") { 
$mem_name = test_input($_GET["mem-name"]); 
$mem_expires = test_input($_GET["mem-expires"]); 
$mem_rating = test_input($_GET["mem-rating"]); 
$mem_ID = test_input($_GET["mem-ID"]); 
$mem_class = test_input($_GET["mem-class"]); 

$array = array( 

"Class" => $mem_class, 
"Rating" => $mem_rating, 
"ID" => $mem_ID, 
"Name" => $mem_name, 
"Expires" => $mem_expires 


); 

$json = file_get_contents('/home/verlager/public_html/cccr_mems.json'); 

$json = preg_replace('/\s{0,}var\s{0,}members\s{0,}=\s{0,}/', '', $json); 
$json = preg_replace('/];\s{0,}/', ']', $json); 

$json_data = json_decode($json,true); 

array_push($json_data, $array); 

$encodedJson = json_encode($json_data); 

$myNewJson = 'var members =' . $encodedJson . '];';

file_put_contents('/home/verlager/public_html/cccr_mems.json', $myNewJson, LOCK_EX); 

echo json_encode($encodedJson); 

} 
?>

这几乎有效,但不完全有效。什么是令人满意的解决方案?

您可以使用array_push()将数组的另一个元素添加到现有数组中。如果js脚本使用对php页面的AJAX调用,php页面将把json字符串发送回调用js页面。然后你可以用它做任何你想做的事

<?php
    // define variables and set to empty values
    $mem_name = $mem_expires = $mem_rating = $mem_ID = $mem_class = "";
    if ($_SERVER["REQUEST_METHOD"] == "GET") {
        $mem_name = test_input($_GET["mem-name"]);
        $mem_expires = test_input($_GET["mem-expires"]);
        $mem_rating = test_input($_GET["mem-rating"]);
        $mem_ID = test_input($_GET["mem-ID"]);
        $mem_class = test_input($_GET["mem-class"]);
    }    
    // Clean up data
    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    // Read JSON file
    $json = file_get_contents('cccr_mems.json');
    //Decode JSON
    $json_data = json_decode($json,true);
    //Print data print_r($json_data); <=== WORKS
    //Here I want to push the GET vars to json members w/o writing to disk!

    //Create an element of the array.
    $array = array(

      "Class"   => $mem_class,
      "Rating"  => $mem_rating,
      "ID"      => $mem_ID,
      "Name"    => $mem_name,
      "Expires" => $mem_expires


    );

    array_push($json_data, $array); //Add the element to the $json_data array.

    //print_r($json_data);  //Shows the results as a php array. 

    echo json_encode($json_data); //Shows results as json string.
    //This is what will get sent back to the calling js page.


?> 

1.由于$json_数据是一个关联数组,因此函数 array_push($json_数据,array('Class'=>$mem_Class]); 可用于将变量添加到数组中

  • 使用json_encode将数组转换回json

  • 如果不想重新加载页面,可以使用客户端的Ajax调用将表单数据发送到PHP脚本,并返回在步骤2中创建的json对象

        $.ajax({
        url: '/handle_form_data.php',
        type: 'POST',
        dataType: "json",
        data: {
            name: $('#name').val(),
            expires: $('#expires').val(),
            id: $('#ID'').val()   //all form variables which need to be sent 
        },
    success:function(response){
    //Do stuff with json object returned from step 2
    }
    });
    
  • 或者如果我正确理解你的问题,
    如果您不想重新加载页面,也不想在后端保存表单数据,则可以在前端JavaScript中编写
    test\u input()函数
    ,在表单字段中的值上运行,并将结果添加到成员的数组中。此操作不需要服务器调用

    是的,但新项目从未出现在“成员”中。。。您是从php脚本中执行这些操作,还是从另一个文件中调用php脚本。请更好地解释一下你的例子是如何发生的。警告:array_push()希望参数1是array,在第38行的/home/verlager/public_html/assets/welcome.php中给出null。我是从php脚本中执行此操作的。第38行=array_push($json_data,$array)//将元素添加到$json_数据数组中。
        $.ajax({
        url: '/handle_form_data.php',
        type: 'POST',
        dataType: "json",
        data: {
            name: $('#name').val(),
            expires: $('#expires').val(),
            id: $('#ID'').val()   //all form variables which need to be sent 
        },
    success:function(response){
    //Do stuff with json object returned from step 2
    }
    });