如何访问表单数据,从一个HTML页面传递与jQuery.ajax()的各个值,PHP脚本里面?(Ho

2019-10-31 18:16发布

我传递表单数据的PHP脚本处理通过JS( jQuery.ajax()

问题是-我不能想出一个办法来访问PHP内个体形态的控制值(如$_POST['zipcode']

相反,我只能访问数据$_POST['form']其被表示为一个长字符串(例如一个完整的形式string(89)"color=red&color=blue&zipcode=12345..." )。

我如何才能获得通过JS从HTML表单传递PHP脚本中的表单数据的各个值?

的index.php(形式)的

 <form id="myform">
    <select name="color" id="color">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
    </select>
    <input type="text" id="zipcode" name="zipcode" />
    <input type="submit" id="submit" name="submit" value="Submit" />
    </form>

的index.php(JS)

$('#myform').on('submit', function(e) {
                    e.preventDefault();
                    $.ajax({
                        type: 'POST',
                        dataType: 'html',
                        url : 'PHPscript.php',
                        data: {form : $('#myform').serialize()}
                    }).done(function(data) {
                         var myJSONresult = data;
                         alert(myJSONresult);
                    });
                });

PHPscript

<?php
if(isset($_POST["form"])){
$form = $_POST["form"];

$myzipcode = $_POST['zipcode']; // won't work; will be null or empty

echo json_encode($form);

}
?>

编辑 邮政编码字段:

$("#zipcode").focus(function(){
                    if(this.value == "zipcode"){
                        $(this).val("");
                    }
                }).blur(function(){
                    if(this.value == ""){
                        $(this).val("zipcode");
                    }
                });

Answer 1:

您需要在表格数据,而不是顺序使用serializeArray()。 这将提交一个数组。

data: $('#myform').serializeArray()

HTML

<input type="hidden" name="action" value="submit" />

PHP

if(isset($_POST["action"]))
{
    //code
}


Answer 2:

添加dataType: 'json'到你的Ajax处理程序,并进一步修改这样的代码:

$.ajax({
    type: 'POST',
    dataType: 'json', // changed to json
    url : 'PHPscript.php',
    data: {form : $('#myform').serialize()},
    success : function(data){ // added success handler
     var myJSONresult = data;
     alert(myJSONresult.yourFieldName);
    }
});


Answer 3:

设置传统的像真

$.ajax({
traditional:true,
//your rest of the ajax code
});

在PHP结束时,你所得到的值罚款问题是在表单系列化结束



文章来源: How to access individual values of form data, passed from an HTML page with jQuery.ajax(), inside a PHP script?