我使用的是last.fm api。我有一个JavaScript AJAX函数,它是这样的,
function showart(art) {
if (art=="") {
document.getElementById("info").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("info").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","5.php?a="+art,true);
xmlhttp.send();
}
这是我称之为的PHP代码
for($i=1;$i<=10;$i++) {
echo '<table><td width="36px">';
echo '<img src="'.$info->topartists->artist[$i-1]->image.'"></td>';
echo '<td><a class="artist" href=# onclick=showart('''.$info->topartists->artist[$i-1]->name.''')>'.$info->topartists->artist[$i-1]->name.'</a></td></table>';
}
每当$info->topartists->artist[$i-1]->name
在艺术家的名字中有一个空格时,例如"Mobb Deep",函数就不会被调用,如果艺术家的名字是"Adele",函数就会被调用。如何解决此问题?
您必须对参数值进行编码:
xmlhttp.open("GET","5.php?a=" + encodeURIComponent(art), true);
这将对空间进行正确编码,服务器将对其进行解码
edit创建<a>
标记的代码没有将"onclick"属性值放在引号中,因此当解析HTML时,事件处理程序代码最终会被破坏。你应该引用代码:
echo '<td><a class="artist" href=# onclick="showart('''.$info->topartists->artist[$i-1]->name.''')">'.$info->topartists->artist[$i-1]->name.'</a></td></table>';
注意在showart()
调用周围添加的"
引号。