這裏是我的代碼:阿賈克斯後沒有返回響應
<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相同,但它不起作用。爲什麼?
你能幫我嗎?
在此先感謝!
迴應是JSON – joyBlanks
作爲joyBlanks說這不是一個正確的JSON響應。您應該始終添加錯誤回調或使用[deferred.fail](https://api.jquery.com/deferred.fail/)回調來捕獲請求錯誤 –
是否響應字符串或數組? – guest271314