PHP文件不返回.responseText中的文本

时间:2013-11-25 04:31:59

标签: javascript php ajax

所以我必须要文件。一个javascript文件,它向一个假定返回JSON的PHP文件发出AJAX请求。我已经使用打印声明测试了PHP文件,并且确实制作了JSON。但是在javascript中,request.responseText为空。

使用Javascript:

var mCurrentIndex = 0;
var request = new XMLHttpRequest();
var mImages = [];
var json;
var url = "fiveMostRecent.php";
request.open("GET", url, true);
request.send();
request.onreadystatechange = function(e)
{
    if(request.readyState == 4 || request.readyState == 2){
        console.log(request.responseText);
        json = JSON.parse(request.responseText);
        console.log(json);
        for(var x = 0; x < json.length; x++){
            var gImage = new GalleryImage();
            gImage.title = json[x].title;
            gImage.price = json[x].price;
            gImage.description = json[x].description;
            gImage.img = new Image();
            gImage.img.src = json.images[x].imgPath;
            makeGalleryImageOnloadCallback(gImage);
            mImages.push(gImage);
        }
    }
    console.log(mImages);
}

PHP:

<?php
session_start();
$con = mysql_connect("localhost", "listAdmin", "hermes");
if(!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("GregsList", $con)
    or die("Unable to select database:" . mysql_error());

$query = "SELECT title, description, price FROM Listings ORDER BY dateListed DESC LIMIT 5";

$result = mysql_query($query);

#converts to json
$rows = array();
while($r = mysql_fetch_assoc($result)) 
{
        $rows[] = $r;
}

#print json_encode($rows);
return json_encode($rows);

?>

1 个答案:

答案 0 :(得分:2)

使用echo json_encode($rows);代替return json_encode($rows);