2016-06-08 87 views
0

我在jQuery中有一个onclick和post函数,我将两个变量传递给我的PHP函数。从javascript发送数组到PHP函数并读取它的值

功能看起来像以下:

$(".pop-save-us").click(function(){ 
    console.log(checkbox_events); 
    console.log(user_id); 
    // alert("Button save pressed"); 
    $.post('/user/AddRemoveBrandUsers', { brands: JSON.stringify(checkbox_events),userId:user_id} , function(data) { 
     if(checkbox_events.length==0) 
     { 
      alert("No changes were made.") 
     } 
     else { 
      if (data == "ok") { 
      alert("ok"); 
      } 
     } 
    }); 

}); 

第一个值是在以下格式的数组:

的console.log(checkbox_events)给出以下输出:

[2: "checked", 4: "checked", 5: "checked"] 

我请执行JSON.stringify(checkbox_events)将我的数组转换为JSON格式并将其传递给我的PHP函数,如下所示:

public function AddRemoveBrandUsersAction() 
    { 
     $brands = $this->getRequest()->getPost("brands"); 
     $userId = $this->getRequest()->getPost("userId"); 
     for($i=0;$i<count($brands);$i++) 
     { 
     // how can I now access each value of the brands array 
     // I need both key and value... How do I access them ?? 
     } 
     die("ok"); 
    } 
+1

所以,你想使用一个'foreach($ array为$ key => $ value)'? – Epodax

+0

好的,你能回答一个答案的形式,以便我可以接受你的回答....我怎样才能得到循环内的“检查”值? – perkes456

+0

“检查”值是什么意思?如果您指的是复选框或收音机,那么值/输入仅在被检查时才被发送? – Epodax

回答

1

使用的代码如下:

if(!empty($brands) && sizeof($brands) > 0){ 
    foreach($brands as $key => $value){ 
     ... 
    } 
} 
+0

好吧$ key将会是= 2的值......但是我怎样才能得到循环内的“checked”字符串值? :) – perkes456

+0

$ value'checked'text –

+0

and $ key is = 2? :) – perkes456

0

您应该使用

json_decode(%your_string_with_json%) 

功能,让您的JSON字符串的内部PHP表示。因此,您将能够操作它(获取数据,设置数据)。使用调试器也非常有用。

$a = json_decode('{"foo": 123, "bar": null, "baz": "qwerty", "arr": ["hello", "world"]}', true); 

会给你和数组,你可以在你的代码中方便地使用:

array (
    'foo' => 123, 
    'bar' => NULL, 
    'baz' => 'qwerty', 
    'arr' => 
    array (
    0 => 'hello', 
    1 => 'world', 
), 
) 

例如:

​​

然后,你应该看你从接收到的值请求,并根据它,使用if ... else ...等。