2013-06-23 84 views
0

我製作了數組$latent_weights_array,我希望當按鈕'save'通過ajax運行一個php腳本時,通過$ _GET變量。通過Ajax通過json_encode獲得PHP數組

在PHP

在031instsql.php

<?php 
    if (isset($_GET['latentweights'])){ 
     echo $_GET['latentweights']; 
     $kati=array(); 
     $kati=json_decode($_GET['latentweights'],true); 
    } 
?> 

1.爲什麼JavaScript的

function ajaxWeight(latentweights){ 
    // trim code here 

    var queryString = "?latentweights=" + latentweights; 

    ajaxRequest.open("GET", "031instsql.php" + 
           queryString, true); 
    ajaxRequest.send(null); 
} 

<?php 
    echo "<input type='button' class='btn' 
      onclick='ajaxWeight(".json_encode($latent_weights_array).")' value='Save'/>"; 
?> 

似乎不工作? 2.這裏需要做什麼?

+0

你檢查你的錯誤控制檯? –

+0

您可以使用Firebug或Chrome Developer工具來檢查您的ajax請求。 – brpaz

+0

我的控制檯沒有錯誤 – Stam

回答

0

json_encode爲數組定義生成有效的JavaScript代碼,所以在傳遞一個數組到ajaxWeight。在它裏面你試圖用一個字符串來連接它,但是JavaScript並沒有爲你做任何的jsonification。見how to make JSON string在JS或者如果你並不需要一個實際的JS對象上執行任何操作,您可以雙擊編碼它在PHP端:

json_encode(json_encode($latent_weights_array)) 

這樣一來,你會路過字符串ajaxWeight可被連接到您的網址。

+0

我不知道爲什麼...但它的工作! – Stam

+0

你能解釋一下爲什麼它使用雙重編碼? – Stam

+0

我想我已經在我的答案中解釋了它...總之第一次編碼產生的字符串在JS中使用時將被視爲數組,第二次編碼該字符串將在JS中產生字符串,並且只能串聯字符串。 –

0

看起來像你的JavaScript AJAX調用應該像這樣:

function ajaxWeight(latentweights){ 
    // trim code here 

    xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
     // Deal with response 
    } 
    } 

    var queryString = "?latentweights=" + latentweights; 

    xmlhttp.open("GET", "031instsql.php" + queryString, true); 
    xmlhttp.send(); 
} 

或者更好的是,使用jQuery

$.getJSON({ 
     url: "031instsql.php", 
     {latentweights: latentweights}) 
.done(function(result){ 
// Deal with result 
}) 
.fail(function(jqxhr, textStatus, errorResponse) { 
    var error = textStatus + ', ' + errorResponse; 
    console.log("Request Failed: " + errorResponse); 
}); 

我想你也需要渲染$kati從PHP的響應。

0

您可以使用jQuery來實現此目的。試試這個

<?php 
    $latent_weights_array = array(1,2,3); 
    echo '<input type="button" class="btn" onclick="ajaxWeight('.json_encode($latent_weights_array).')" value="Save"/>'; 
?> 


<script type="text/javascript"> 
    function ajaxWeight(latentweights){ 
     $.ajax({ 
      type: "GET", 
      url: "031instsql.php", 
      data: 'latentweights='+latentweights, 
      success: function(html){ 
       alert(html); 
      } 
     }); 
    } 
</script> 

更多關於jQuery AJAXREAD THIS