2016-08-24 77 views
-1

我有一個JavaScript對象像下面PHP - 如何訪問通過jQuery的AJAX傳遞的對象

var customerinfo = { 
      customer_name : $('#customer_name').val(), 
      customer_address: $('#customer_address').val(), 
      customer_city : $('#customer_city').val(), 
      customer_state : $('#customer_state').val(), 
      customer_zip : $('#customer_zip').val(), 
     }; 

然後我試圖通過,使用$就喜歡到PHP下面

$.ajax({ 
        url: "../folder/file.php", 
        type: "POST", 
        data: { 
        'customerinfo' : customerinfo, 
        }, 
        success:function(){ 
         window.location = "file.php"; 
        } 
      }) 

在PHP我嘗試打印物體出來

$customerinfo = json_decode($_POST['customerinfo']); 
print_r($customerinfo); 

$customerinfo = $_POST['customerinfo']; 
print_r($customerinfo); 

我得到undefined index customerinfo

我也試過在javascript來json.stringify傳遞之前,但得到同樣的錯誤。

我發現了一個非常類似的帖子如 jquery ajax object array php,但我不能讓代碼工作either.I認爲AJAX能夠通過傳遞數據,只是我不知道如何把它在PHP端進行解碼。

我知道我可以從HTML提交按鈕發佈它,但這是一個更大的問題簡化測試,我想使用jquery傳遞裏面有很多對象的對象。

如果JavaScript端是正確的,問題是"how to access objects passed through jquery ajax in PHP."

如果沒有,問題是"how to pass objects from javascript to php."

+0

'成功:功能(數據){doSomethingWith(數據); }' – developerwjk

+0

我不想從PHP獲得響應。我其實想要做一個重定向。所以我只是把它放在成功。 – codenoob

回答

0

從我所看到的問題可能是在數據中。 嘗試用靜態數據發佈,這意味着

var customerinfo = { 
     customer_name : $('#customer_name').val(), 
     customer_address: $('#customer_address').val(), 
     customer_city : $('#customer_city').val(), 
     customer_state : $('#customer_state').val(), 
     customer_zip : $('#customer_zip').val(), 
    }; 

var customerinfo = { 
     customer_name : 'ddd', 
     customer_address: 'ddd', 
     customer_city : 'ddd', 
     customer_state : 'ddd', 
     customer_zip : 'ddd' 
    }; 

也嘗試從瀏覽器控制檯發送AJAX替代,這樣你就可以看到這些數據被張貼