7

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

我的代码如下所示:

var jsonData;

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

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

有任何想法吗?

4

5 回答 5

14

尝试放入dataType: 'json'你的ajax调用:

var jsonData;

$.ajax({
        url: 'data.php',
        dataType: 'json',
        success: function(response) {
            jsonData = response;
        }
});
于 2013-10-20T09:47:18.577 回答
2

您也可以使用此机制:

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

如果您只想获取 JSON,它会更干净 :)

于 2013-10-20T09:49:56.503 回答
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 备忘单

于 2013-10-20T10:20:21.720 回答
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() .'}}'; 
}

阿贾克斯

 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) {}

        });
于 2013-10-20T10:36:47.803 回答
0

数据.php

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

$.ajax({
        url: 'data.php',
        dataType: 'json',
        success: function(response) {
            jsonData = response;
        }
});
于 2013-10-20T09:48:51.543 回答