[英]Sending an array to PHP function from javascript and reading its values
我在jQuery中有一個onclick和post函數,我將兩個變量傳遞給了我的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");
}
使用代碼如下:
if(!empty($brands) && sizeof($brands) > 0){
foreach($brands as $key => $value){
...
}
}
你應該用
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',
),
)
例如:
$b = $a['foo'] // b = 123
$b = $a['arr'][0] // b = hello
然后,您應該查看從請求中收到的值,並根據它使用if ... else ...等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.