简体   繁体   English

使用 ajax 将数组值从 PHP 传递到 JavaScript

[英]Pass array values from PHP to JavaScript using ajax

I have a PHP file which includes an array its data retrieved from the database.我有一个 PHP 文件,其中包含从数据库中检索到的数据的数组。

this is the array in PHP file dashboard.php这是 PHP 文件dashboard.php的数组

echo $stat= json_encode(array( 
    0 => $posts['tot'], 
    1 => $partners['pap'], 
    2 => $messages['mem'], 
));

the output of this array will be: ["12","5","11"]该数组的输出将是: ["12","5","11"]

on the other side, I have a javascript file which supposed to receive these data using ajax and after that output it into object data to be displayed in a chart on the dashboard.php page另一方面,我有一个 javascript 文件,它应该使用 ajax 接收这些数据,然后将其输出到对象数据中,以显示在dashboard.php页面上的图表中

this is ajax code in the javascript file:这是javascript文件中的ajax代码:

function () {
        $.ajax({
            url: 'dashboard.php',
            type: 'get',
            data: { n1: n1, n2: n2, n3: n3 },
            dataType: 'JSON',
            success: function (response) {

                // selecting values from response Object
                var n1 = response.n1;
                var n2 = response.n2;
                var n3 = response.n3;
            }
        });
    });

I know there is something missing which how to define the data coming from the PHP file which this is my problem I couldn't figured it out.我知道缺少一些如何定义来自 PHP 文件的数据,这是我的问题,我无法弄清楚。

I have looked into many tutorials but I'm still confused and I can't get it.我已经查看了很多教程,但我仍然感到困惑,无法理解。

thanks.谢谢。

In your PHP output:在您的 PHP 输出中:

["12","5","11"]

All three values are clearly strings.所有三个值显然都是字符串。

All you need to do is cast/convert them into number (using intval or similar) before being sent back to client-side:您需要做的就是在将它们发送回客户端之前将它们转换/转换为数字(使用intval或类似方法):

echo $stat = json_encode(array( 
    0 => intval($posts['tot']), 
    1 => intval($partners['pap']), 
    2 => intval($messages['mem']), 
));

Next, you have another problem where the server is passing back an array, but the client is trying to read it as if it's an object, hence you will never get the values.接下来,您遇到了另一个问题,即服务器传回一个数组,但客户端试图将它当作一个对象来读取,因此您将永远无法获得这些值。

Since the data being passed back to server is an array ["12","5","11"] , in the client, you will want to retrieve it the array way:由于传回服务器的数据是一个数组["12","5","11"] ,在客户端,您将希望以数组方式检索它:

{
  ...otherAjaxOptions,
  success: function(response){
    var n1 = response[0];
    var n2 = response[1];
    var n3 = response[2];

    /* or using ES6 way */

    var [n1, n2, n3] = response;
  }
}

If the response is not an array, then your server is probably transforming the responses into a more structured object.如果response不是数组,那么您的服务器可能正在将响应转换为更结构化的对象。 In that case, simply check where the array is inside the response , and retrieve it the same way.在这种情况下,只需检查数组在response ,并以相同的方式检索它。

Consider redefining the keys of the associative array as required by the ajax script, namely 'n1', 'n2', 'n3'.考虑根据 ajax 脚本的要求重新定义关联数组的键,即“n1”、“n2”、“n3”。

Remove the closing parenthesis and semicolon after ajax and rewrite ajax into a function that returns response from success function handler.去掉 ajax 后面的右括号和分号,将 ajax 改写成一个函数,从成功函数处理程序返回响应。

Also return the result of ajax call from function after naming the function, right now it is an anonymous unnamed function.命名函数后也返回函数调用ajax的结果,现在它是一个匿名的未命名函数。 Unless you want to invoke using an Immediate Invoked Function Expression (IIFE) then use除非您想使用立即调用函数表达式 (IIFE) 进行调用,否则请使用

(function(){})();

index.html索引.html

<html> 
  <head> 
    <title>Ajax</title>
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
      <script>
        function ajax() {
          return $.ajax({
            url: 'dashboard.php'
          }).done(function(response) {
              // selecting values from response Object
              var n1 = response.n1;
              var n2 = response.n2;
              var n3 = response.n3;
              return response;
            });
        }
        $('document').ready(function(){  
            ajax().then(function(result){
              $("body").html("<pre>"+result+"</pre>");
            });
          });
      </script>
  </head>
  <body>
  </body>
</html>

dashboard.php仪表盘.php

<?php
    $posts = [];
    $partners = [];
    $messages = [];

    $posts['tot'] = '12';
    $partners['pap'] = '5';
    $messages['mem'] = '11';


    echo json_encode(array( 
        'n1' => $posts['tot'], 
        'n2' => $partners['pap'], 
        'n3' => $messages['mem'] 
    ));

See demo on glitch https://glitch.com/~twilight-glow-cheque查看故障演示https://glitch.com/~twilight-glow-cheque

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

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