PHP数组通过Ajax通过json_encode

时间:2013-06-23 10:37:57

标签: php jquery ajax arrays json

我已经制作了数组$latent_weights_array,我希望当我按下'save'按钮通过ajax运行一个php脚本时,传递的是$ _GET变量。

PHP中的

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

在javascript中

function ajaxWeight(latentweights){
    // trim code here

    var queryString = "?latentweights=" + latentweights;

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

in 031instsql.php

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

1.为什么似乎不起作用? 2.这里需要做什么?

3 个答案:

答案 0 :(得分:0)

json_encode为数组定义生成有效的JavaScript代码,因此您将数组传递给ajaxWeight。在它内部,你试图用字符串连接它,但JavaScript不会为你做任何jsonification。请参阅JS中的how to make JSON string或者如果您不需要实际的JS对象来对其执行任何操作,您可以在php端对其进行双重编码:

json_encode(json_encode($latent_weights_array))

这样,您就可以将字符串传递给可以连接到您网址的ajaxWeight

答案 1 :(得分: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);
 });

我认为您还需要为PHP的响应呈现$kati

答案 2 :(得分: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 AJAX READ THIS

的更多信息