繁体   English   中英

通过json_encode通过Ajax实现PHP数组

[英]PHP array through Ajax via json_encode

我已经制作了数组$latent_weights_array ,当我希望按钮“保存”通过ajax将are作为$ _GET变量传递给ajax时,它会运行php脚本。

在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);
}

在031instsql.php中

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

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

json_encode为数组定义生成有效的JavaScript代码,因此您ajaxWeight数组传递给ajaxWeight 在其中,您尝试将其与字符串连接,但是JavaScript不会为您做任何jsonification。 查看如何在JS中制作JSON字符串 ,或者如果您不需要实际的JS对象对其执行任何操作,则可以在php端对其进行双重编码:

json_encode(json_encode($latent_weights_array))

这样,您将把字符串传递给可以连接到URL的ajaxWeight

看起来您是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

您可以使用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更多信息,请阅读此内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM