【问题标题】:grabbing an encoded array from a file using ajax使用ajax从文件中获取编码数组
【发布时间】:2014-12-06 21:35:46
【问题描述】:

我试图使用以下代码从文件中获取编码数组[{"got":"1235.00","needed":"4350"}]

function getNewValues(){
        $.ajax({
            dataType: 'json',
            url: 'get.php',
            type: 'POST',
            cache: false
        })
        .success(function(data) {
            return data;
        })
        .fail(function() {
            console.log("An error ocurred");
        })
    }

但问题是我在return data 中返回的唯一内容是array( object ),问题是我不知道出了什么问题或在哪个文件中出错了。

生成编码数组:

<?php
  $pdo = new PDO('mysql:host=127.0.0.1;dbname=thermometer', 'root', ''); 
  $sql = 'SELECT `got`.`value` AS got, `needed`.`value` AS needed FROM `needed`, `got`'; 
  $statement = $pdo->prepare($sql);
  $statement->execute();
  $result = $statement->fetchAll(PDO::FETCH_ASSOC);
  $json = json_encode($result);
  print_r($json);
?>

如果有人对此有解决方案,那就太好了,因为我无法解决它。

【问题讨论】:

  • 在浏览器中打开您的 PHP 文件,您会很容易看到返回的内容...
  • php 文件打印 [{"got":"1235.00","needed":"4350"}] 当我尝试使用 ajax 抓取它时,它变成了 array( object )。我正在尝试制作一个无需刷新页面即可获取新数据的脚本。但它不会工作:(
  • 请向我们展示您的 json 数组的 var_dump
  • 如果我运行 var_dump 这就是我得到的string(35) "[{"got":"1235.00","needed":"4350"}]"
  • 所以它返回一个数组,因为它是一个数组。您如何尝试使用return data;?您很可能需要遍历数组才能使用它或单独解析键/值。

标签: php arrays ajax


【解决方案1】:

您的问题是函数在数据到达时已经完成。这是由于 AJAX 的异步特性。您需要处理您的数据何时到达,而不是假设它已经到达。

function getNewValues(){
    $.ajax({
        dataType: 'json',
        url: 'get.php',
        type: 'POST',
        cache: false
    })
    .success(function(data) {
        // Handle your data here;
    })
    .fail(function() {
        console.log("An error ocurred");
    });

 // Attempting to use the data or returning the data here will not work!
}

【讨论】:

    【解决方案2】:

    编辑:重读您的问题。想想this response 类似的问题可能会有所帮助。

    一旦你执行了准备好的语句,类似这样的东西就可以代替 PDO::FETCH_ASSOC 工作

    ...
    $result = $statement->execute();
    for ($file_data = array(); $row = $result->fetch_assoc(); $file_data[] = $row);
    

    $file_data 就是你想要的任何数据的关联数组。

    print json_encode($file_data);
    

    【讨论】:

    • 我无法让它工作它拒绝运行fetch_assoc() 命令。不能调用对象是我得到的。
    【解决方案3】:

    你需要在函数内部设置并返回变量,而不是试图将ajax返回值作为函数返回。换句话说,将ajax返回传递给一个变量到一个函数变量,然后返回它。像这样的:

    function getNewValues(){
       var returnedJSON= $.ajax({
            dataType: 'json',
            url: 'get.php',
            type: 'POST',
            cache: false
        })
        .success(function(data) {
            return data;
        })
        .fail(function() {
            console.log("An error ocurred");
        })
       return returnedJSON;
        }
    

    【讨论】:

    • 我可以使用data[0].got 获取数据,但现在的问题是,当我将数据返回到显示为undefined variable 的新变量时,我无法获取比console.log() 更远的数据。
    • 当你得到undefined variable时发布你拥有的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2017-07-02
    • 2015-04-15
    相关资源
    最近更新 更多