用撇号改变PHP字段

时间:2016-09-15 03:59:27

标签: javascript php

我有以下表格,当用户从<select>中选择一个选项时,javascript将其输入“名称”字段。它完美地工作,除非选项包含撇号,它仅在撇号之前将其截断。我已经尝试将selectedValue = selectedValue.replace(/'/g, \"\\'\");添加到javascript中,但它没有帮助。任何建议将不胜感激。

#related form objects
echo "<br><br>Name: <input type=\"text\" name=\"name\" id=\"name\" value=\"$name\" size=\"50\">";

  echo "<br>Nearby Suggestions: <select name='nearby' id='nearby'>"; $places=file_get_contents('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='.$lat.','.$long.'&key=xxx&radius=80');
  $output= json_decode($places,true);
  foreach($output['results'] as $place){
    echo "<option value='$place[name]'>$place[name]</option>";
  }
  echo "</select>";


  #script to enter nearby field into name field upon selection
  echo "
<script>$(document).on('change','#nearby',function(){
    var x = document.getElementById(\"nearby\"),
    selectedValue = x.value;
    selectedValue = selectedValue.replace(/'/g, \"\\'\");
    $('input[name=name]').val(selectedValue);
    });</script>";

2 个答案:

答案 0 :(得分:0)

您没有转发来自googleapis通话的值。因此,当您在Jim's Place标记中盲目加载<option>之类的值时,生成的代码为:

<option value='Jim's Place'>Jim's Place</option>

包含3个撇号并且已损坏。首先转换值。

foreach($output['results'] as $place){
  $place_converted = htmlspecialchars($place['name'], ENT_QUOTES);
  echo "<option value='$place_converted'>$place_converted</option>
}

正确生成:

<option value='Jim&#039;s Place'>Jim&#039;s Place</option>

答案 1 :(得分:0)

echo "<option value='$place[name]'>$place[name]</option>"; 

导致报价不匹配。尝试用

替换它
echo "<option value=\"$place[name]\">$place[name]</option>";

您可以转义包含值的双引号。