无法从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,但仍然无法访问响应的数据对象。

有任何想法吗?

尝试将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页面的顶部重复此操作:

  

也可以看看:

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