Ajax POST - 不返回JSON响应

时间:2015-08-21 15:53:48

标签: javascript php jquery ajax json

这是我的JavaScript:

$.ajax({
    url: './checkcolors.php',
    type: 'post',
    data: {
        url: '<?php echo $LINK;?>',
        SizeId: SelectedSizeID
    },
    dataType: 'json',
    success: function (data) {
        $('.ColorImagesNOColor').fadeIn();
        $('#LoadingImage').hide();
        data.forEach(function(id){
            $('#' + data["colorids"]).hide();
        });
    }
});

这是checkcolors.php代码:

<?PHP
    $url = $_POST['url'];
    $SizeId = $_POST['SizeId'];    

    if(isset($_POST['url']))
    {   
        libxml_use_internal_errors(true); 
        $doc = new DOMDocument();
        $doc->loadHTMLFile($url);

        $xpath = new DOMXpath($doc);

        $DataVariants = $xpath->query('//span[@class="ImgButWrap"]/@data-variants')->item(0)->nodeValue;

        $jsonStart = strpos($DataVariants, '[');
        $jsonEnd = strrpos($DataVariants, ']');

        $collections = json_decode(substr($DataVariants, $jsonStart, $jsonEnd - $jsonStart + 1));   

        foreach ($collections as $item) {
            $ColVarId = $item->ColVarId;

            $SizeNames = [];
            foreach ($item->SizeVariants as $size) {
                $SizeNames[] = $size->SizeName;
            }

            if (in_array($SizeId, $SizeNames)) {
                echo json_encode(array('colorids' => $ColVarId));
            }


        }
    }   

?>

结果必须返回许多ID,这些ID对应于我必须隐藏的HTML <div></div>元素的ID。不知怎的,我没有得到checkcolors.php的正确答复。没有浏览器控制台错误。

你能帮我解决这个问题吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

而不是:

if (in_array($SizeId, $SizeNames)) {
    echo json_encode(array('colorids' => $ColVarId));
}

使用此:

if (in_array($SizeId, $SizeNames)) {
    $result[] = $ColVarId;
}

在foreach之前:

$result = array();

在foreach之后:

echo json_encode($result);

现在你已经有一个看起来像JS成功的数组:

["1", "2", "3"] ...

您的脚本应该是:

data.forEach(function(id){
    console.log(id); // will log: 1
});

答案 1 :(得分:0)

如果没有加载的html / xml文件的源数据,则无法找到错误。可能你已经破产了。我建议你在变量赋值的每一行之后添加&#34; echo&#34; s或#34; print_r&#34; s或#34; var_dump&#34; s 。因此,您将看到数据显示失真的位置。

相关问题