0

如何通过 json 将多个返回的 mysql 行传递给下面的 jquery 脚本?使用到目前为止我编写的代码,当我将 2 或更多传递给它时,我无法让 jquery 成功回调函数执行。我将如何实现这一目标?

jQuery, Js 代码:

$("#projects").click(function() {
    jQuery.ajax({ type: "POST", dataType: "JSON",
        url: "<?=base_url()?>index.php/home/projectsSlider",
        json: {returned: true}, success: function(data) {
            if (data.returned === true) {
                $("#content").fadeOut(150, function() {                             
                    $(this).replaceWith(projectsSlider(data.projectId, data.projectName, data.startDate, data.finishedDate, data.projectDesc, data.createdFor, data.contributors, data.screenshotURI, data.websiteURL), function() {
                        $(this).fadeIn(150);
                    });
                });
            }
        }
    });
});

php代码:

function projectsSlider() {
    $query  = $this->db->query("SELECT * FROM projects ORDER BY idprojects DESC");
    foreach ($query->result() as $row) {
        $projectId = $row->projectId;
        $projectName = $row->projectName;
        $startDate = $row->startDate;
        $finishedDate = $row->finishedDate;
        $createdFor = $row->createdFor;
        $contributors = $row->contributors;
        $projectDesc = $row->projectDesc;
        echo json_encode(array('returned' => true,
            'projectId' => $projectId,
            'projectName' => $projectName,
            'startDate' => $startDate,
            'finishedDate' => $finishedDate,
            'projectDesc' => $projectDesc,
            'createdFor' => $createdFor,
            'contributors' => $contributors));
    }
    $query1 = $this->db->query("SELECT * FROM screenshots s WHERE s.projectId = '{$projectId}' ORDER BY s.idscreenshot DESC");
    foreach ($query1->result() as $row2) {
        $screenshotURI = $row2->screenshotURI;
        $websiteURL = $row->websiteURL;
        echo json_encode(array('screenshotURI' => $screenshotURI,'websiteURL' => $websiteURL));
    }
}
4

2 回答 2

2

您正在回显两个不同的 JSON 字符串。这将不是一个有效的 JSON。因此(虽然我没有测试过),ajax 调用会失败。

我建议你合并这两个 JSON 并从“projectsSlider()”函数中只返回一个有效的 JSON。像这样:

$projectArray = $this->getProjectsRowSet();
$screenshotsArray = $this->getScreenshotsRowSet();
$combinedArray = array_merge(array("Projects" =>$projectArray),array("Screenshots" =>$screenshotsArray));
echo json_encode($combinedArray);

然后使用“data.Projects”和“data.Screenshots”从 ajax 回调方法中访问每个行集。像这样:

$("#resultProjects").html(JSON.stringify(data.Projects));
$("#resultScreenshots").html(JSON.stringify(data.Screenshots));
于 2012-07-12T01:24:32.610 回答
1

有效的 JSON 字符串基本上是 JS 代码块中赋值语句的右侧。您在 foreach() 循环中生成了多个独立的 JSON 字符串,并且基本上产生了类似的东西

var x = 1; 2; 3; 4; 5; 6;

这是一个明确的语法错误。您正在生成无法解析的 json。

您的循环应该构建一个单一的整体 PHP 数据结构,然后在循环完成后对其进行 json_encode:

$data = array();
foreach($query1->result() as $row2) {
   $data[] = array($row2->screenshotURI, $row->websiteURL);
}
echo json_encode($data);
于 2012-07-10T23:52:14.433 回答