繁体   English   中英

如何在PHP脚本中访问使用jQuery.ajax()从HTML页面传递的表单数据的各个值?

[英]How to access individual values of form data, passed from an HTML page with jQuery.ajax(), inside a PHP script?

我正在将表单数据传递给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");
                    }
                });

您需要在表单数据上使用serializeArray()而不是序列化。 那将作为数组提交。

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

HTML

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

PHP

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

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);
    }
});

将传统设为真像

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

在php端,您可以得到很好的值,问题出在表单序列化端

暂无
暂无

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

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