javascript - 如果调用函数时提供的参数包含空格,则不会调用函数

标签 javascript php last.fm

我正在使用 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/

相关文章:

javascript - 如何修改api响应

javascript - 如何在 Node.js 中存储 100GB 的内存

java - 安卓,http : How to upload a file to a site hosted by a shared server?

php - 如何将一个存储过程中的值用于另一个存储过程?

javascript - 有没有办法在 JavaScript 加载之前不加载 html?

java - 在 Java 中使用 XPath 获取当前节点值

java - Web 服务 API - 请求用户授权 - 第一定时器

javascript - 如何为一个 scrollspy 位置指定不同的 scrollTop 值?

javascript - Ember JS 错误处理 : Accessing errors in model not possible due to adapter error

javascript - 从last.fm API 访问JSON