将ajax关联数组传递给php关联数组

时间:2013-04-10 15:28:52

标签: php jquery ajax arrays associative

我正在尝试通过$ .ajax方法将表单值传递给PHP。我在html中有以下表格:

<form>
<p>
   <label for="login">User ID:</label>
   <input type="text" name="login" id="login" value="user name">
</p>

<p>
   <label for="password">Password:</label>
   <input type="password" name="password" id="password" value="password">
</p>
</form>

和ajax:

$("form").submit(function(event) {
 var formInput = $('form').serialize();// tried with serializeArray() also

 var request = $.ajax({
    type: "POST",
    url:"../some.php", 
    data: {formInput:formInput},
    statusCode: {
                404: function() { alert("file not found");}}

 });

PHP:

<?
$data = $_POST['formInput'];
$data = array();
parse_str($_POST, $data);
print_r($data);
?>

在控制台上打印:

(
     [Array] =>
)

我想要的是将$ data作为关联数组:

$data = array(
        'login' => 'foo'
        'password' => 'bar'
        );

但似乎$ data正在作为字符串处理...... 先感谢您!

5 个答案:

答案 0 :(得分:2)

使用data: $('form').serializeArray()代替data: {formInput:formInput},

然后在php方面,$_POST只是你想要的数据。

答案 1 :(得分:2)

您需要指定一个关联数组而不是json_decode中的对象:

json_decode($data, true);

您可能还需要这样做 -

$('form').serializeArray();

答案 2 :(得分:1)

而不是:

$("form").submit(function(event) {
 var formInput = $('form').serialize();// tried with serializeArray() also

 var request = $.ajax({
    type: "POST",
    url:"../some.php", 
    data: {formInput:formInput},
    statusCode: {
                404: function() { alert("file not found");}}
 });

使用它:

$("form").submit(function(event) {
 var formInput = $('form').serialize();// tried with serializeArray() also

 var request = $.ajax({
    type: "POST",
    url:"../some.php", 
    data: formInput,
    statusCode: {
                404: function() { alert("file not found");}}
 });

答案 3 :(得分:1)

我们想要的是序列化到一个可以解码的json对象。使用THIS插件即可访问.serializeObject

$("form").submit(function(event) {
 var formInput = $('form').serializeObject();
 formInput = JSON.stringify(formInput);

 var request = $.ajax({
    type: "POST",
    url:"../some.php", 
    data: {formInput:formInput},
    statusCode: {
                404: function() { alert("file not found");}}

 });

然后在php端你可以轻松解码JSON

$data = json_decode($_POST['formInput'], true);

答案 4 :(得分:0)

从很好的回答中我发现了我的问题。 当我提交POST时,我将数组放入数组中。

以下ajax代码:

$("form").submit(function(event) {
var formInput = $('form').serialize();// tried with serializeArray() also

var request = $.ajax({
type: "POST",
url:"../some.php", 
data: {formInput:formInput},
statusCode: {
            404: function() { alert("file not found");}}
});

更改为:

$("form").submit(function(event) {
var formInput = $('form').serializeArray();

var request = $.ajax({
type: "POST",
url:"../some.php", 
data: formInput,
statusCode: {
            404: function() { alert("file not found");}}
});

PHP改为:

<? $data = $_POST;
    print_r($data); ?>

关于cosole它正好打印了我想要的东西:

Array
(
[login] => admin
[password] => qwerty123!
)

感谢大家快速回复