繁体   English   中英

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

[英]Can't get json data from jQuery ajax call

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

我的代码看起来像这样:

var jsonData;

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

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

有任何想法吗?

尝试将dataType: 'json'放在你的ajax调用中:

var jsonData;

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

您也可以使用此机制:

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

如果你想只获得JSON,它会更干净:)

您应该在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备忘单

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

        });

data.php

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM