无法从jQuery ajax调用中获取json数据

7

我正在尝试通过jQuery ajax调用从data.php获取数据。

我的代码如下:

var jsonData;

$.ajax({
        url: 'data.php',
        success: function(response) {
            jsonData = response;
        }
});

我的data.php文件返回JSON格式的数据,但其中一些文本以Unicode格式编码。

我已经在data.php和JavaScript文件上设置了字符集,但仍无法访问响应的数据对象。

有什么想法吗?


1
你是不是在调用 $.ajax() 后立即尝试访问 jsonData 变量?此时它将是 undefined,因为你的 ajax 调用是异步的。请在 success 处理程序内进行处理。(如果不是这样,请单击“编辑”并添加有关在此情况下“无法访问”实际意味着什么的详细信息。你的 response 变量中实际上会出现什么?) - nnnnnn
5个回答

14

尝试在您的ajax调用中添加dataType: 'json':

var jsonData;

$.ajax({
        url: 'data.php',
        dataType: 'json',
        success: function(response) {
            jsonData = response;
        }
});

2

您也可以使用这种机制:

$.getJSON( "data.php", function( response ) {
    jsonData = response;
});

如果你只想得到JSON,那么更简洁的方法是:


哦,我甚至不知道那个函数存在... 很好知道 :) - asifrc

1
你应该使用PHP中的header()函数来设置正确的响应头(内容类型和字符集):
header('Content-type: application/json; charset=UTF-8');

您还应该在HTML页面顶部重复此操作:

<meta http-equiv="Content-type" value="text/html; charset=UTF-8" />

另请参阅:

PHP UTF-8 cheatsheet


1

PHP

try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->query('SET NAMES utf8;');
    $stmt = $dbh->prepare($sql);  
    //$stmt->bindParam("id", $_GET[id]);
    $stmt->execute();

    $advice = $stmt->fetchAll(PDO::FETCH_OBJ);
    $dbh = null;
    echo '{"items":'. json_encode($advice) .'}'; 
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
}

Ajax
 var temp;
    $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: serviceurl,
            data: "{'userName':'" + userName + "' , 'password': '" + password                                   
                   + "'}",
            dataType: "json",
            success: function(msg) {
                            temp = jQuery.parseJSON(msg.d);
                          },
            error: function(xhr, ajaxOptions, thrownError) {}

        });

0

data.php

header('Content-type: application/json'); 

$.ajax({
        url: 'data.php',
        dataType: 'json',
        success: function(response) {
            jsonData = response;
        }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接