2016-08-19 30 views
0

嗨,大家好我使用ajax時遇到問題。當我在textarea中使用「Script」alert(aaaa)「script」提交表單時,我的表單是錯誤的,現在我不用如何驗證ajax來避免我的問題。感謝您的幫助。 `使用ajax和jquery的firt時間

$(document).ready(function() { 
    $("#sub").click(function (e) { 
     e.preventDefault(); 
     var comment =$("#com").val(); 
     if ($.trim(comment) == "") { 
      alert("u must fill here"); 
      return; 
     } 
     $.ajax({ 
      type: 'json', 
      method: 'POST', 
      headers: { 
       "X-Requested-With": "XMLHttpRequest" 
      }, 
      url: 'http://ivsexpress.net/index.php?controller=postdetail&method=create&post_id=<?php echo $_GET['post_id']; ?>', 
      data: { 
       comment: comment 
      }, 
      success: function(data){ 
       var data = JSON.parse(data); 
       $("#form")[0].reset(); 
       $("#Comment_ajax").prepend($("<div></div>").html(
       '<h4 style="font-size:15px;color:#9f224e">'+ data.full_name +'</h4>'+ 
       '<h6 style="font-style:italic">'+ 'vào lúc: '+ data.created_date+'</h6>'+ 
       '<p style="font-size:13px;text-align:justify;word-break:break-word;">'+ data.content +'</p>'+'<br>' 
       )); 
      }, 
      error: function(data, status, jqxhr){ 
       console.log(status); 
      } 
     }); 
     return false; 
    }); 
}); 

`

+0

請把更多的精力投入到解釋請問有什麼不對? :)看起來像你的新堆棧。 – James111

+0

你是什麼意思**我的表單是錯誤的**? –

+0

哦,我的瀏覽器顯示警報「aaaaaa」,我的評論沒有插入到我的數據庫中。是啊,這是我使用ajax和jquery的時間:'(。 –

回答

0

如果我正確理解這一點,你需要躲避data.content一部分,你是串聯字符串生成HTML元素(這是一個不好的做法)。不管怎麼說,你可以通過使用

var escaped_full_name = $('<p>').append(data.full_name).html(); 
var escaped_content = $('<p>').append(data.content).html(); 
var escaped_created_date = $('<p>').append(data.created_date).html(); 

,並用它作爲

$("#Comment_ajax").prepend($("<div></div>").html(
       '<h4 style="font-size:15px;color:#9f224e">'+ escaped_full_name +'</h4>'+ 
       '<h6 style="font-style:italic">'+ 'vào lúc: '+ escaped_created_date+'</h6>'+ 
       '<p style="font-size:13px;text-align:justify;word-break:break-word;">'+ escaped_content +'</p>'+'<br>' 
       )); 

還是逃吧,我強烈建議不要使用字符串連接創建HTML元素