简体   繁体   English

使用Javascript以JSON格式收集多种表单数据,然后通过AJAX发送到PHP

[英]Collect multiple forms data as JSON with Javascript and send via AJAX to PHP

I am not sure if I am missing the point with JSON because from what I have seen; 我不确定我是否缺少JSON的要点,因为从我所看到的情况来看; tutorials, examples and questions do not involve posting form data via JSON/AJAX to PHP. 教程,示例和问题不涉及通过JSON / AJAX将表单数据发布到PHP。

I see a lot of examples using jQuery but I have not learned jQuery yet because I am told that getting an understanding of Javascript first is best and then use jQuery as shorthand later. 我看到了许多使用jQuery的示例,但我还没有学习jQuery,因为有人告诉我最好先了解Javascript,然后再使用jQuery作为速记。

I can 'collect' my form data and process and output a string which I believe to be JSON syntax. 我可以“收集”表单数据并处理并输出一个我认为是JSON语法的字符串。

"{p1:{'lname':'adsfer','fname':'asdf','email':'ewrt','sex':'male'},p2:{'lname':'erty','fname':'erty','email':'erty','sex':'male'}}"

HTML 的HTML

<form id="p1">
<h2>Add Person 1:</h3> 
Surname: <input type='text' name='lname' value='' ><br>
First Name:<input type='text' name='fname' value='' ><br>
Email: <input type='email' name='email' value=''><br>
Sex:<select name='sex'><option></option><option value='male'>Male</option><option value='female'>Female</option></select> 
</form> 

<form id="p2">
<h2>Add Person 2:</h3> 
Surname: <input type='text' name='lname' value='' ><br>
First Name:<input type='text' name='fname' value='' ><br>
Email: <input type='email' name='email' value=''><br>
Sex:<select name='sex'><option></option><option value='male'>Male</option><option value='female'>Female</option></select> 
</form>
<button onclick='submit_forms()'>Next</button> 

Javascript Java脚本

function submit_forms(){
    var div = "content";
    var url = "contract.php";
    var forms = document.forms;
    var txt = "{";
    for(var i = 0 ;i<forms.length;i++){
        txt += forms[i].id + ':{';
        for(var n=0;n<forms[0].length;n++){
            txt += "'" + forms[i][n].name + "':'" + forms[i][n].value +"',";
        }
        txt = txt.substring(0,txt.length-1);
        txt += '},';
    }  
        txt = txt.substring(0,txt.length-1);
        txt +='}';
    txt = JSON.stringify(txt);
   alert(txt)
   post_JSON_PHP(txt,div,url);
   }

function post_JSON_PHP(vars,div,url){
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById(div).innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader("Content-type", "application/JSON");
    xmlhttp.send(vars);
}

PHP 的PHP

$json = json_decode($_POST['p1']);
var_dump($json);

PHP replies with Notice: Undefined index: p1 for line and NULL. PHP做出以下答复:注意:未定义的索引:行和NULL为p1。

Is it just that I have some wrong syntax or am I totally on the wrong track? 仅仅是我语法错误还是我完全走错了路?

I did not know that when the content type is set to JSON it does NOT give the PHP page POST data, therefore it can not be retrieved with $_POST. 我不知道当内容类型设置为JSON时,它不会提供PHP页面POST数据,因此无法使用$ _POST进行检索。

Using this PHP code worked for me AFTER I removed the stringify function from my javascript 使用此PHP代码为我工作后,我从JavaScript中删除了stringify函数

$json = json_decode(file_get_contents('php://input'),true);
echo $json['p1']['fname'];

In case it helps anyone else, my code above was building JSON text string but I found that it had limitations. 万一它对其他人有帮助,我上面的代码正在构建JSON文本字符串,但是我发现它有局限性。

Instead I built a JavaScript object and then converted that object to JSON using the JSON.stringify function. 相反,我构建了一个JavaScript对象,然后使用JSON.stringify函数将该对象转换为JSON。

This script works even if I amend the form AND it handles ARRAYs of forms with the same name. 即使我修改了表单,并且该脚本处理具有相同名称的表单的数组,该脚本也可以工作。

After researching endlessly I found that there is a jQuery function that does the same thing plus more and probably more elegantly. 经过无休止的研究,我发现有一个jQuery函数可以执行相同的操作,而且功能更多,并且可能更优雅。 However, if you are like me and haven't learned jQuery yet; 但是,如果您像我一样,还没有学习过jQuery,那么, you might find this useful 您可能会发现这很有用

function submit_forms(){
    var div = "content";    //for AJAX call
    var url = "process.php";    //for AJAX call
    var form = document.forms;
    var ppl = {};
    for(var i = 0;i<form.length;i++){
        if (ppl[form[i].name]){
            ppl[form[i].name].push({});
        } else {
            ppl[form[i].name] = [{}];
        }
        var index = ppl[form[i].name].length-1;
        for (var n=0;n<form[i].length;n++){
            ppl[form[i].name][index][form[i][n].name] = form[i][n].value;
        }
    }
    console.log(ppl);
    var vars = JSON.stringify(ppl);
    ajax_json(vars,div,url)

} 

JSON keys and values must be enclosed on double quotes: JSON键和值必须用双引号引起来:

'{ "key": "value1", "key2": "value2", "object": { "prop": "value" } }'
"{ \"key\": \"value1\", \"key2\": \"value2\", \"object\": { \"prop\": \"value\" } }"

After a successful decode on PHP, you should use it as an object, not an array: 在PHP上成功解码后,应将其用作对象,而不是数组:

$class = json_decode('{ "key": "value", "sclass": { "name": "abc", "surname": "xyz" } }');
echo $class->key; // = value
echo $class->sclass; // Error: cannot convert std class to string
echo $class->sclass->name; // = abc

As I understood you are trying to send a row data in request body, so server can't recognise that you are sending a form data, that's why your $_POST array is empty. 据我了解,您正在尝试在请求正文中发送行数据,因此服务器无法识别您正在发送表单数据,这就是$ _POST数组为空的原因。

Check out this link 查看此链接

You should send header Content-type as application/x-www-form-urlencoded and serialise your form data not as json string but as urlencoded. 您应该将标头Content-type作为application / x-www-form-urlencoded发送,并序列化您的表单数据而不是json字符串,而是urlencoded。

xmlhttp.open("POST","ajax_test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

In this case your data will be available in your php script as form data. 在这种情况下,您的数据将在php脚本中作为表单数据提供。

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

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