代码之家  ›  专栏  ›  技术社区  ›  jkeesh

PHP生成的Javascript中的转义撇号

  •  2
  • jkeesh  · 技术社区  · 14 年前

    Yahoo answers 以及许多其他网站。

    echo "<input type=\"text\" 
    onblur=\"if (this.value == '') {this.value = '$cleaned';}\" 
    onfocus=\"if (this.value == '$cleaned') {this.value = '';}\" 
    value=\"$cleaned\" />\n";
    

    我有一个php变量 $cleaned 作为我的初始值。这段代码可以工作,除非变量中有撇号,比如 $cleaned = "FRIEND'S" this.value = 'FRIEND'S' 和撇号 FRIEND'S 提前结束这段关系。

    有人知道怎么处理这个案子吗?

    3 回复  |  直到 14 年前
        1
  •  3
  •   Gumbo    14 年前

    使用 json_encode 对JavaScript和 htmlspecialchars 要对要在HTML属性值中使用的字符串进行编码,请执行以下操作:

    echo '<input type="text"
    onblur="'.htmlspecialchars("if (this.value == '') {this.value = ".json_encode($cleaned).";}").'" 
    onfocus="'.htmlspecialchars("if (this.value == ".json_encode($cleaned).") {this.value = '';}").'"
    value="'.htmlspecialchars($cleaned).' />'."\n";
    

    defaultValue

    echo '<input type="text"
    onblur="'.htmlspecialchars("if (this.value == '') {this.value = defaultValue;}").'" 
    onfocus="'.htmlspecialchars("if (this.value == defaultValue) {this.value = '';}").'"
    value="'.htmlspecialchars($cleaned).'" />'."\n";
    
        2
  •  1
  •   JW.    14 年前

    首先生成纯JavaScript代码。您可以使用 json_encode ,如下所示:

    $js = 'if (this.value == '.json_encode($cleaned).') {this.value = "";}';
    

    htmlspecialchars ,如下所示:

    echo '<input type="text" onblur="'.htmlspecialchars($js).'" />';
    
        3
  •  0
  •   leonardys    14 年前

    这个怎么样

    echo '<input type="text" 
    onblur="if (this.value == "") {this.value = "' . $cleaned . '";}" 
    onfocus="if (this.value == "' . $cleaned . '") {this.value = "";}" 
    value="' . $cleaned . '" />\n';