1

我在正确设置 JSON 帖子以从 php 文件中获取 MYSQL 数据库的行数时遇到困难。当我希望将行数作为整数警报时,我收到“未定义”警报。我一直在使用不同的 stackoverflow 帖子尝试使用 JQuery/AJAX 从 PHP 文件构建这个 Get 变量

这是ajax调用:

// check number of records in Mine
$.ajax({
    url: 'pyrAddToMine.php',
    type: 'POST',
    success : function (result) {
    alert(result['ajax']); // "Hello world!" alerted
    console.log(result['numRec']) // The value of your php $row['numRec'] will be displayed
    },
    error : function () {
        alert("error");
    }
});

这是 pyrAddToMine.php 中的 php 代码: mysql_select_db($database_cms_test, $cms_test); $query = "选择 * 从$favUserTableName"; $result = mysql_query($query) 或 die(); $row = mysql_fetch_array($result); $num_records = mysql_numrows($result);

IF ($num_records >= 15){
    $numRec = array(
        'ajax' => 'Hello world!',
        'numRec' => $num_records,
            );
    echo json_encode($numRec);
    exit;
}

以下是有关 php 文件的更多详细信息:

<?php
require_once('../Connections/cms_test2.php');

...

mysql_select_db($database_cms_test, $cms_test);
$query = "SELECT * FROM `$favUserTableName`";
$result = mysql_query($query) or die();
$row = mysql_fetch_array($result);
$num_records = mysql_numrows($result);

IF ($num_records >= 15){

    $numRec = array(
        'ajax' => 'Hello world!',
        'numRec' => $num_records,
    );
    echo json_encode($numRec);

    exit;
}
...

?>
4

2 回答 2

1

您好,您忘记指定数据类型

   $.ajax({
        url : 'myAjaxFile.php',
        type : 'POST',
        data : data,
        dataType : 'json',
        success : function (result) {
           alert(result['ajax']); // "Hello world!" alerted
           console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
        },
        error : function () {
           alert("error");
        }
    })
于 2013-06-08T04:29:03.127 回答
1

如果您没有设置接受 json 所需的选项,您会收到一个包含 ajax 格式的字符串,并且您没有收到 javascript 中的对象

$.ajax({
    url: 'pyrAddToMine.php',
    type: 'POST',
    /* required for accept json for ajax */
    accepts:'application/json',
    dataType:'json',
    /* */
    success : function (result) {
    alert(result['ajax']); // "Hello world!" alerted
    console.log(result['numRec']) // The value of your php $row['numRec'] will be displayed
    },
    error : function () {
        alert("error");
    }
});
于 2013-06-08T04:37:03.717 回答