如何将数组存储为变量

时间:2015-08-11 23:20:09

标签: javascript php arrays

我试图将从php返回的变量存储到javascript变量中,这是怎么做的?

 var array;
 function test(id)
 {
 $.post( "main/updater.php", { id:id } ).done(function( data ) 
        {
              array = data;
        });
  }

这适用于字符串但不是数组,它不存储任何内容。数据作为数组返回但不存储。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

在php中:

  class User < ActiveRecord::Base
    attr_accessor :remember_token

    before_save {self.email = email.downcase }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 },
                         format:{with: VALID_EMAIL_REGEX}, 
                         uniqueness: { case_sensitive: false }

   has_secure_password
   validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

    has_one :profile, dependent: :destroy

   accepts_nested_attributes_for :profile

end

在javascript中:

class Profile < ActiveRecord::Base
  validates :name, presence: true, length: { maximum: 50 }
  validates :street, :city, :state, :zipcode, presence: true

  belongs_to :user
end

答案 1 :(得分:0)

试试这个

$field_map = array(
    'element_3'  => 'Name',
    'element_2'  => 'E-mail',
    'element_14' => 'City',
    'element_15' => 'Country'
);

$submitted_data = array('fields' => array());    
foreach ( $field_map as $key => $label) 
{
    $submitted_data['fields'][] = array(
        'key'   => $key,             // e.g. element_2
        'label' => $label,           // e.g. E-mail
        'value' => $post_data[$key]  // e.g. john@example.com
    );
}