我需要根据从http://kasaragodyellowpages.com/pagedata.php?id=x返回的 0 或 x 值来替换页面中“标题”类元素的 href 。此 url 设置为 1 以进行测试。可以正确处理 ajax 请求。
问题是迟到的反应和失败的时间
<script type="text/javascript">
$(document).ready(function(){
$('.title').each(function() {
var url = null;
var l = this.href;
id_str= (l.replace('http://www.kasaragodyellowpages.com/index.php?page=item&id=',''));
var loadUrl = "pagedata.php";
$.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
}
}
);
if(url){
console.log('set data for '+url);
$(this).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
}
});
});
</script>
如图所示,在从循环设置值之后设置 ajax 结果,无需等待 ajax 成功
在此之后我替换为when
<script type="text/javascript">
$(document).ready(function(){
$('.title').each(function() {
var url = null;
var l = this.href;
id_str= (l.replace('http://www.kasaragodyellowpages.com/index.php?page=item&id=',''));
var loadUrl = "pagedata.php";
$.when($.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
}
}
))
.then(if(url){
console.log('set data for '+url);
$(this).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
});
});
});
</script>
但这没有用