2012-03-24 18 views
1

我嘗試序列化我的複選框項目。在Ajax中對php進行數組化處理

首先,我想告訴你我想要什麼。

我有一個這樣的形式,

enter image description here

用戶選擇checboxes當按下它的按鈕「實」移除藝術家。

我準備一個AJAX腳本,這是

function deleteData2() 
{ 
    var artistIds = new Array(); 

    $(".p16 input:checked").serialize()(function(){ 
     artistIds.push($(this).attr('id')); 
    }); 


    $.post('/json/crewonly/deleteDataAjax2', { 'artistIds': artistIds },function(response){ 
     if(response=='ok') 
      alert("ok"); 
    }); 


} 

我的AJAX腳本有電影ID和藝術家ID,它有這些DATAS。實際的問題是,ajax無法將這些數據發送到php。我做了一些研究,然後我達到了我必須序列化我的陣列並添加我的$(".p16 input:checked").serialize()(function(){腳本序列化,但也不起作用。

public function deleteDataAjax2() { 

     extract($_POST); 

     if (isset($artistIds)) 
      $this->sendJSONResponse('ok'); 

    } 

上面的代碼是我的PHP。和artistIds總是空的,所以我的序列化功能不起作用。

什麼可能是錯誤的?我怎樣才能達到我的藝術家在PHP方面?

編輯

最後,我來到這個

var artistIds = new Array(); 

    $(".p16 input:checked").each()(function(){ 
     artistIds.push($(this).attr('id')); 
    }); 


    $.post('/json/crewonly/deleteDataAjax2', JSON.stringify({ 'artistIds': artistIds }),function(response){ 
    if(response=='ok') 
     alert("ok"); 
    }); 

,並在PHP端,

public function deleteDataAjax2() { 

     extract($_POST); 

     $a = json_decode($artistIds); 

     if (!empty($a)) 
      $this->sendJSONResponse('ok'); 

    } 

它仍然是錯誤的

+0

你能給出$ _POST變量的數據嗎? – 2012-03-24 22:04:19

回答

2
$(".p16 input:checked").serialize()(function(){ 
    artistIds.push($(this).attr('id')); 
}); 

這仍然給你artistids數組,所以你不能將其發送給服務器,你需要將其轉換成JSON格式的第一,那麼你可以把它提交給服務器這樣

$.post('/json/crewonly/deleteDataAjax2', JSON.stringify({ 'artistIds': artistIds }),function(response){ 
    if(response=='ok') 
     alert("ok"); 
}); 

,並確保使用它使用json_decode功能

1
$(".p16 input:checked").serialize()(function(){ 
artistIds.push($(this).attr('id')); 
}); 

我覺得這些線路不工作,因爲我嘗試過Chrome上,他們給我一個錯誤之前解碼在服務器JSON數據。 我想你可能想使用jQuery的each function做類似:

$(".p16 input:checked").each(function(){ 
    artistIds.push($(this).attr('id')); 
}); 
$.post('/json/crewonly/deleteDataAjax2', { 'artistIds': artistIds },... 

之後,你將有$artistIds設置爲PHP數組。

extract method不建議使用請求變量,因爲它可能會引入一些安全漏洞。