我正在使用 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);
这将正确编码空间,服务器将对其进行解码。
编辑 创建 <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()
的引述打电话。
关于javascript - 如果调用函数时提供的参数包含空格,则不会调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34341264/