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

时间:2013-10-20 09:46:21

标签: javascript jquery ajax json

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

我的代码如下所示:

var jsonData;

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

我的data.php文件正在返回json格式的数据,但某些文本是Unicode格式。 我在data.php和我的javascript文件上设置了charset,但仍然无法访问响应的数据对象。

有什么想法吗?

5 个答案:

答案 0 :(得分:14)

尝试将dataType: 'json'放入您的ajax调用中:

var jsonData;

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

答案 1 :(得分:2)

您也可以使用此机制:

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

如果你想只获得JSON,那就更干净了。)

答案 2 :(得分:1)

您应该在header()中使用PHP函数来设置正确的响应标头(内容类型和字符集):

header('Content-type: application/json; charset=UTF-8');

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

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

另见:

PHP UTF-8 cheatsheet

答案 3 :(得分: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) {}

        });

答案 4 :(得分:0)

data.php

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

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