我在从我的 PHP 代码中取回响应时遇到问题。JavaScript 文件说 JSON 对象的长度为 0。
这是我从getalbums.php脚本返回的 JSON:
[
{
"album_id": "50ab2c3db9396",
"username": "tusik",
"title": "testalbum",
"cover_photo_url": "http:\/\/s3.amazonaws.com\/Looking_Glass_Images\/tusik_testalbum_testpic.jpeg"
},
{
"album_id": "50ab3b75a46fe",
"username": "tusik",
"title": "test",
"cover_photo_url": "http:\/\/s3.amazonaws.com\/Looking_Glass_Images\/tusik_test_test.png"
}
]
获取相册.php
<?php
session_start();
include("db.php");
$albumsArray = array();
$username = $_GET['uid'];
//Preventing MySQL injection
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$sql = "SELECT album_id,username,title,cover_photo_url FROM albums WHERE albums.username='$username'";
$result = mysql_query($sql) or die(mysql_error());
echo $count;
while ($row = mysql_fetch_object($result)) {
$albumsArray[] = $row;
}
echo json_encode( $albumsArray );
?>
如果我输入/getalbums.php?uid=tusik
,我会从上面得到 JSON,所以我知道该页面有效。
相册.js
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
var username = $.urlParam('uid');
var data = "uid=" + username;
$.ajax({
type: "GET",
url: "getalbums.php",
data: data,
dataType: "json",
processData: false
}).done(function(data) {
//Do work
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
代码给了我这个错误。
TypeError: Cannot read property 'album_id' of undefined
谁能看到我做错了什么?
编辑:
修复了我的问题 jeroen 的建议部分正确。{'uid':username}
应该读{"uid":username}
。