【问题标题】:AJAX response, cant alert JSON String properlyAJAX 响应,无法正确警告 JSON 字符串
【发布时间】:2017-05-08 12:54:48
【问题描述】:

我发现了一个奇怪的问题。

使用 php 我在 mysql 数据库上运行选择查询,我试图将其返回到我的 ajax 调用,以便我可以循环遍历它,但我总是得到未定义的警报,我可以提醒整个 json 字符串,但不能定位值。

Ajax 代码:

        $.ajax({
            type: "POST",
            url: 'database_data.php',
            data: {
                action: 'ct',
                input: input
            },
            success: function (data) {
                var obj = JSON.parse(data);
                alert(obj[0].pid);
                alert(data[0].pid);
            },error: function(request, status, error){
                alert("Error: Could not delete");
            }
        });

PHP 代码:

$base= mysqli_connect($dbhost,  $dbuser, $dbpass, $dbbase);
if ($_POST['action']== "ct"){
  $input = $_POST['input'];
  $return_arr = array();
  $sql = "SELECT pid FROM programmes WHERE complete_title LIKE '%$input%' LIMIT 30";

if ($result = mysqli_query( $base, $sql )){
    while ($row = mysqli_fetch_assoc($result)) {
        $row_array['pid'] = $row['pid'];
        array_push($return_arr,$row_array);
    }
}

mysqli_close($base);

echo json_encode($return_arr);

}

警报数据给出这样的响应:

[{"pid":"p00547jm"},{"pid":"p0054880"},{"pid":"p005492h"},...

如果我选择提醒 data[0], data[1] 它会打印每个单独的字符

【问题讨论】:

  • $.ajax({ dataType: "json", url: url, data: data, success: success }); 添加dataType,或使用简写:api.jquery.com/jquery.getjson
  • 您正在提醒data[0] 未解析。
  • obj 是一个数组,所以你需要在那里使用正确的索引:obj[0].pid
  • @CBroe ,最初它也不是那样工作的,我在提交问题时没有将其编入索引的原因是因为我正在尝试所有可能性哈哈

标签: javascript php mysql json ajax


【解决方案1】:

您可以使用dataType 告诉 jquery 您期望从服务器返回什么。见http://api.jquery.com/jquery.ajax/

你的情况

   $.ajax({
            type: "POST",
            url: 'database_data.php',
            dataType: 'json',
            data: {
                action: 'ct',
                input: input
            },
            success: function (data) {
                var obj = data; // I should already be json!
                alert(obj.pid);
                alert(data.pid);
            },error: function(request, status, error){
                alert("Error: Could not delete");
            }
        });

【讨论】:

    【解决方案2】:

    这是因为您可能会收到字符串作为响应。所以你的datastring

    您可以使用JSON.parse() 将其解析为 JSON 对象并像这样访问数据,

    data = '[{"pid":"p00547jm"},{"pid":"p0054880"},{"pid":"p005492h"}]';
    
    console.log(JSON.parse(data)[0].pid);

    【讨论】:

    • @bigbounty 他仍然需要先访问正确的数组元素。
    猜你喜欢
    • 2016-08-28
    • 1970-01-01
    • 2016-06-08
    • 2018-03-30
    • 1970-01-01
    • 2016-02-08
    • 2020-06-20
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多