【问题标题】:PHP array through Ajax via json_encode通过 json_encode 通过 Ajax 的 PHP 数组
【发布时间】:2013-06-23 10:37:56
【问题描述】:

我已经创建了数组$latent_weights_array,我希望当我按下“保存”按钮以通过 ajax 运行 php 脚本时,将 are 作为 $_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);
}

在 031instsql.php 中

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

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

【问题讨论】:

  • 您检查过控制台是否有错误吗?
  • 您可以使用 Firebug 或 Chrome 开发者工具检查您的 ajax 请求。
  • 我的控制台没有错误

标签: php jquery ajax arrays json


【解决方案1】:

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

json_encode(json_encode($latent_weights_array))

这样,您将向ajaxWeight 传递字符串,该字符串可以连接到您的网址中。

【讨论】:

  • 我想我已经在我的回答中解释过了...简而言之,第一次编码产生在 JS 中使用的字符串将被视为数组,该字符串的第二次编码将在 JS 中产生字符串,并且只有字符串可以连接。
【解决方案2】:

看起来你的 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

【讨论】:

    【解决方案3】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 2012-04-14
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      相关资源
      最近更新 更多