[英]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
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.