如何防止从textarea输入提交脚本

时间:2016-11-29 18:47:46

标签: javascript

如何阻止仅向数据库提交脚本,但应使用我正在使用的以下脚本来允许所有HTML标记。请帮忙。

<form name="exthtmlForm" style="height: 100%;">
  <fieldset>
    <legend>Source Editor</legend>
    <div id="editor" name="editor" style="height: 100%;">
      <textarea id="iExthtml" style="max-width: 100%; width: 100%; height: 50px; box-sizing: border-box;">
        <?php if($exthtml_content!=""){ echo htmlentities($exthtml_content, ENT_QUOTES, 'UTF-8'); } ?>
      </textarea>
    </div>
  </fieldset>
</form>

$(document).on('click','#abtSubmit',function(){
  var data = $('#iExthtml').val().replace(/'/g, "\\'");
  dataString=$('form[name=exthtmlForm]').serialize();
  $.ajax({
    type: 'POST',
    url: "<?php echo $GLOBALS['base_url'];?>ajax/cpanel/cpanel-ajax.php?mode=UpdateExthtml",
    cache: false,
    data: { content : data , dpid : <?php echo $dpid; ?> , menuID : <?php echo $MPage; ?> },  
    dataType: "json",
    success: function(data){
      if(data.success == "yes"){
        if($("#states").length!==1){
          $(".error_2525").remove();
          $('#abtSubmit').before("<div class='error_2525' id='success_message' style='margin-top: 10px;'>Content updated successfully</div>");
          $('#success_message').delay(5000).fadeOut(300, function(){
            $('#success_message').remove();
          });
        }
      }
    }
  });
});

1 个答案:

答案 0 :(得分:0)

完成此任务有两个步骤。首先,您需要提取textarea的默认值并将其存储在javascript变量

jQuery(document.ready(function(){
    window.form_exthtmlForm_default = '<?php echo (($exthtml_content!="") ? htmlentities($exthtml_content, ENT_QUOTES, 'UTF-8') : ""); ?>';
}));

然后你需要在提交时使用这个变量(window.form_exthtmlForm_default)以确保表单没有传递默认值。

修改提交功能:

$(document).on('click','#abtSubmit',function(){
  var data = $('#iExthtml').val().replace(/'/g, "\\'");

  //Here we will return false if the form has the default textarea value.    
  if ($('#iExthtml').val() == window.form_exthtmlForm_default) {
      //You would want to also provide some sort of frontend 
      //user message to alert the user to populate the text
      return false;
  }

  dataString=$('form[name=exthtmlForm]').serialize();
  $.ajax({
    type: 'POST',
    url: "<?php echo $GLOBALS['base_url'];?>ajax/cpanel/cpanel-ajax.php?mode=UpdateExthtml",
    cache: false,
    data: { content : data , dpid : <?php echo $dpid; ?> , menuID : <?php echo $MPage; ?> },  
    dataType: "json",
    success: function(data){
      if(data.success == "yes"){
        if($("#states").length!==1){
          $(".error_2525").remove();
          $('#abtSubmit').before("<div class='error_2525' id='success_message' style='margin-top: 10px;'>Content updated successfully</div>");
          $('#success_message').delay(5000).fadeOut(300, function(){
            $('#success_message').remove();
          });
        }
      }
    }
  });
});