2013-03-05 99 views
0

我想在JavaScript中處理PHP數組。這是我使用的代碼。使用jQuery將PHP數組轉換爲JavaScript AJAX

Array.php

<?php 

$sentido[1]="ver"; 
$sentido[2]="tocar"; 
$sentido[3]="oir"; 
$sentido[4]="gustar"; 
$sentido[5]="oler"; 


?> 

fx_funciones.js

/*Pre-sentences*/ 
var js_array=new Array(); 

$.ajax({   
     type: "POST", 
     url: "array.php", 
     success: function(response) { 
      js_array=response  
     } 
    }); 

這是我想做的事情,但它不工作。

+0

嘛,你不數組創建後,做任何事情。嘗試添加'echo json_encode($ sentido)' – DiMono 2013-03-05 15:26:18

+0

可能的重複[從php數組獲取數據 - AJAX - jQuery](http://stackoverflow.com/questions/6395720/get-data-from-php-array-ajax- jQuery) – 2013-03-05 15:32:03

回答

0

我認爲,對於上述問題的答案已經被處理了下面的鏈接。請檢查出來。 Get data from php array - AJAX - jQuery

我希望它會幫助你

+0

如果您認爲現有的問題及其答案爲這個問題提供了答案,那麼您應該將問題標記爲重複。 – 2013-03-05 15:29:37

0

試試這個:

<?php 

$sentido[1]="ver"; 
$sentido[2]="tocar"; 
$sentido[3]="oir"; 
$sentido[4]="gustar"; 
$sentido[5]="oler"; 

echo json_encode($sentido); 

和:

$.getJSON('array.php', function(sentido) { 
    console.log(sentido); 
}); 
0

你需要數組從你的PHP代碼JSON返回,使用json_encode功能。然後,在你的jQuery代碼,指定json的dataType所以,它的隱式轉換和傳遞給回調函數作爲數組:

var js_array=new Array(); 

$.ajax({   
    type: "POST", 
    url: "array.php", 
    success: function(response) { 
     js_array=response  
    }, 
    dataType: 'json' 
}); 
0

使用標準的JSON符號。它序列化對象和數組。然後打印出來,在客戶端上取出並解析它。

在服務器上:

echo json_encode($sentido); 

更多關於PHP的json_encode:http://php.net/manual/de/function.json-encode.php

在客戶端,這是特別容易,如果你使用了AJAX意想不到JSON編碼的對象jQuery的功能,爲你解析它們:

$.getJSON('address/to/your/php/file.php', function(sentidos) { 

    alert(sentidos[0]); // It will alert "ver" 
    alert(sentidos[1]); // It will alert "tocar" 

}); 

它使用GET,但這很可能是你需要的。

更多關於jQuery的$ .getJSON:http://api.jquery.com/jQuery.getJSON/