【问题标题】:Returned JSON data undefined when using PDO with bindParam将 PDO 与 bindParam 一起使用时返回的 JSON 数据未定义
【发布时间】:2014-04-27 23:04:16
【问题描述】:

我一直在用 stackoverflow 来解决这个问题。我正在使用 jQuery 的 ajax 方法发送一些表单数据,并使用 PDO 根据表单输入准备和返回数据。我在准备好的语句中有一个参数,它取自表单数据,并使用 PDO bindParam 方法设置。

使用表单数据,我得到的json数据是未定义的。如果我硬编码字符串参数而不是使用表单数据,我会取回我正在寻找的数据。我已经回显出我传入的变量的确切值和类型,它与硬编码字符串相同。我已经尝试明确设置编码以确保它也是 utf8。

这就是我的 php 的样子(编辑:包括执行方法,它包含在我的代码中,但最初在帖子中被遗漏了):

$endorsers = array();
// Takes in the values from checkbox form data
foreach($_POST as $k => $v) {
  if($v == 'on') {
    $endorsers[] = $k;
  }
}

// Set variable to first checkbox value
$endorser = $endorsers[0];

try {
  $connection = new PDO('mysql:host=localhost;dbname=*****;charset=utf8', $username, $password);
  $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $statement = $connection->prepare('SELECT DISTINCT c.name AS cand_name, e.name AS end_name FROM candidates c JOIN end_cand ec ON (ec.end_id = c.id) JOIN endorsements e ON (e.abbrev = :endorser)');
  $statement->bindParam(':endorser', $endorser, PDO::PARAM_STR);
  $statement->execute();

  $results = $statement->fetchAll();

  if (isset($results)) {
    echo json_encode($results);
  } else {
    $error = array('error_message' => 'Sorry, Charlie');
    echo json_encode($error);
  }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

还有 ajax:

$("document").ready(function() {
    $("form").submit(function(e) {
      e.preventDefault();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: "get-endorsements.php",
            success: function(data) {
                console.log(data[0]);
                console.log(data[1]);
            }
        })
    })
});

如果我执行常规表单提交只是为了查看回显的 json 编码结果,无论是使用硬编码字符串还是表单数据,我都会得到相同的结果 - 它是这种形式:

[{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}]. 

虽然使用表单数据变量时,通过 ajax 返回的数据是未定义的,但我无法弄清楚为什么会有所不同。

解决方案:

  $("form").submit(function(e) {
      e.preventDefault();
      var data = $(this).serialize();
      console.log(data);
        $.ajax({
            type: "POST",
            //contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: data,
            url: "get-endorsements.php",
            success: function(data) {
                console.log(data[0]);
                console.log(data[1]);
            }
        })
    })

必须通过$.ajax 传递数据(感谢@David-SkyMesh),并且不设置 contentType(因为这是传递给服务器的数据的 contentType,而不是接收到的数据)。让我自己很困惑地认为数据可以简单地通过$_POST 变量 b/c 获得,当然,当我使用表单上的标准 post 方法而不是通过 Ajax 测试 PHP 返回值时。

【问题讨论】:

  • 您是否使用 Chrome 开发者工具/Firebug/Fiddler 检查了实际的 HTTP 响应?
  • 它正在返回 html/text,所以我在我的 php 中添加了一个标头以将内容类型设置为 json。虽然没有改变结果,我的数据仍然未定义。
  • @nicolekanderson 我是在想象吗,或者您是否从未将要发布的表单数据(即:您的要 JSON 化的数据结构)传递给 .ajax(...)?我看到了配置属性、URL 和回调,但没有数据?
  • 所以你是说只有当你使用 bindParm 时它是未定义的,但它在 harcoded 时才有效?

标签: php jquery ajax json


【解决方案1】:

我认为你输了:

$results->执行();

之前

$results = $statement->fetchAll();

$endorsers = array();
// Takes in the values from checkbox form data
foreach($_POST as $k => $v) {
  if($v == 'on') {
    $endorsers[] = $k;
  }
}

// Set variable to first checkbox value
$endorser = $endorsers[0];

try {
  $connection = new PDO('mysql:host=localhost;dbname=*****;charset=utf8', $username, $password);
  $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $statement = $connection->prepare('SELECT DISTINCT c.name AS cand_name, e.name AS end_name FROM candidates c JOIN end_cand ec ON (ec.end_id = c.id) JOIN endorsements e ON (e.abbrev = :endorser)');
  $statement->bindParam(':endorser', $endorser, PDO::PARAM_STR);

  $results->execute();
  $results = $statement->fetchAll();

  if (isset($results)) {
    echo json_encode($results);
  } else {
    $error = array('error_message' => 'Sorry, Charlie');
    echo json_encode($error);
  }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

【讨论】:

  • 对,很抱歉在清理我的故障排除代码时被删掉了。我更新了我的帖子。
猜你喜欢
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 2022-01-13
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多