这是我的代码:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var ColorId = "1";
$( "#targetButton" ).click(function() {
$.ajax({
url: 'checkcolors.php',
type: 'post',
dataType: 'json',
success: function (data) {
var arr = data.msg.split(',');
arr.forEach(function(id){
$('#' + id.trim()).hide();
});
//$('#target').html(data.msg);
},
data: ColorId
});
});
});
</script>
<button type="button" id="targetButton">Send</button>
<div class="BlackAndWhite" id="24604682">24604682</div>
<div class="BlackAndWhite" id="24604682x">24604682x</div>
<div class="BlackAndWhite" id="24604679">24604679</div>
<div class="BlackAndWhite" id="24604621">24604621</div>
以下是checkcolors.php的结果:
24604603, 24604684, 24604640, 24604609, 24604682, 24604686, 24604681, 24604689, 24604602, 24604679, 24604680, 24604622, 24604685, 24604683, 24604621, 24604677, 24604688,
以下是来自checkcolors.php的代码:
<?PHP
$url = 'http://www.sportsdirect.com/dunlop-mens-canvas-low-top-trainers-246046?colcode=24604622';
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("7", $SizeNames)) {
echo "$ColVarId, ";
}
}
?>
当我点击按钮时,我正在观看浏览器控制台是否有任何警告或错误,但没有。不知怎的,它不起作用,我不知道为什么。
它应该隐藏所有div元素与checkcolors.php响应给出的相同ID,但它不起作用。为什么?
你能帮帮我吗?
提前致谢!
答案 0 :(得分:1)
尝试更改此行:
var arr = data.msg.split(',');
到此:
var arr = data.split(',');
答案 1 :(得分:0)
在您的php脚本“checkcolors.php”中,您必须返回一个JSON文件。
<xsl:template match="p">
<p name="myname" id="999" sec="{@sec}">
<xsl:apply-templates/>
</p>
</xsl:template>
然后在你的javascript中,用数据替换arr。
$res = array();
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
$SizeNames = [];
foreach ($item->SizeVariants as $size) {
$SizeNames[] = $size->SizeName;
}
if (in_array("7", $SizeNames)) {
$res[] = $ColVarId;
}
}
echo json_encode($res);