简体   繁体   English

无法通过jQuery ajax发布Javascript数组

[英]Unable to post Javascript array via jQuery ajax

I am extremely reluctant to ask this question as I know it is something really stupid I am missing, but I simply cannot get this to work. 我非常不愿意提出这个问题,因为我知道这确实是我所缺少的愚蠢之举,但是我根本无法解决这个问题。 Code below: 代码如下:

<script>

var formArray = new Array();
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";

$('#my_button').click(function() {
    $.ajax({
        type: "POST",
        url: "scheduler.php",
        data: formArray,
        success: function(response){

            console.log(response);

        }
    });
});
</script>

Server side PHP Script scheduler.php 服务器端PHP脚本scheduler.php

<?php

    print_r($_POST);

?>

All I get back logged to the console is an empty array: 我重新登录到控制台的所有内容都是一个空数组:

Array
(
)

If I console.log formArray within the click function it shows the complete array just fine. 如果我在click函数中使用console.log formArray ,它将显示完整的数组。 So why is it not posting it to my PHP file? 那么为什么不将其发布到我的PHP文件中呢?

Thanks in advance 提前致谢

Changing Array() to Object() would work as well. Array()更改为Object()也可以。

You would get: 您将获得:

Array
(
    [start] => one
    [stopat] => two
    [stop_at] => three
)

You are adding string properties to an array, which is for storing numeric indices. 您正在将字符串属性添加到用于存储数字索引的数组。

Use an object instead: 改用一个对象:

var formArray = {};
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";

jQuery will iterate over the indices in an array, using a for (var i = 0; i < formArray.length; ++i) loop, which will completely miss any properties you've added to the array. jQuery将使用for (var i = 0; i < formArray.length; ++i)循环遍历数组中的索引,这将完全丢失您添加到数组中的所有属性。

Also, new Array should have been [] (as {} should be preferred over new Object ). 另外, new Array应该是[] (因为{}应该比new Object更可取)。 Don't use the new X method of initialization for built-in types. 不要对内置类型使用new X初始化方法。 (Crockford, The Good Parts) (克罗福德,好零件)

JavaScript Arrays are designed to hold an ordered sequence of items with integer keys. JavaScript数组设计为使用整数键保存项目的有序序列。 When jQuery converts a data structure into Form URL Encoded data and encounters an array, it will iterate over those integer keys and not over named keys. 当jQuery将数据结构转换为Form URL Encoded数据并遇到数组时,它将遍历那些整数键而不是命名键。

Use an Object if you want to have named keys . 如果要命名键,请使用对象

Change new Array() to newObject() new Array()更改为newObject()

Edit your Ajax like this and see if it works: data: {data: formArray}, dataType: 'JSON' 像这样编辑您的Ajax,看看它是否有效: data: {data: formArray}, dataType: 'JSON'

$.ajax({
        type: "POST",
        url: "scheduler.php",
        data: {data : formArray},
        dataType: 'JSON'
        success: function(response){

            console.log(response);

        }
    });

PHP: PHP:

print_r($_POST['data']);

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

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