当前位置: 代码迷 >> JavaScript >> KendoUI模板中的表单(Ajax)发布
  详细解决方案

KendoUI模板中的表单(Ajax)发布

热度:54   发布时间:2023-06-05 09:36:30.0

我需要在KendoUI模板中创建一个Form Post(Ajax),不幸的是没有成功。

<form id="commentSubmit">
  <div class="form-group">
   <textarea class="form-control k-textbox" name="body" id="bodyComment"></textarea>
   <input type="hidden" name="post_id" id="post_idComment" value="#= id #" />
  </div>
  <div class="form-group">
   <button class="k-button k-primary" type="submit">Add Comment</button>
  </div>
</form>

我们有一个ID为#commentSubmit的Ajax帖子脚本,但是它不起作用。

$(document).ready(function() {
$('#commentSubmit').submit(function() {
$.ajax({
   url: "url.to.post",
   method: "POST",
   dataType: "json",
   data: {
   "body": $("#bodyComment").val(),
    "post_id" : $("#post_idComment").val()
   },
....

我们在互联网上发现了类似

<form action="http://url.to.post" data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="\#template" id="form0" method="post"> 

但是它重定向到URL,而这是我们不想要的。

有什么建议吗?

更改此:

  1. idclass

     <form class="commentSubmit"> 
  2. 这里也:

     $(document).on('submit', '.commentSubmit', function() { 
  3. 阻止表单提交:

     $(document).on('submit', '.commentSubmit', function(e) { e.preventDefault(); 

这应该使任何添加了带有commentSubmit类模板的表单的提交commentSubmit可以被ajax请求拦截和处理。

提示:使用jQuery的来获取整个表单数据:

$.ajax({
    data: $(this).serialize() // Being 'this' the form when inside the 'submit' event

尝试这个:

<form method="post" id="commentSubmit" name="commentSubmit" action="#" autocomplete="off" enctype="multipart/form-data">
  <div class="form-group">
    <textarea class="form-control k-textbox" name="body" id="bodyComment"></textarea>
    <input type="hidden" name="post_id" id="post_idComment" value="#= id #" />
    <button type="submit" class="k-button k-primary" id="btnSubmit" form="commentSubmit">Add Comment</button>
  </div>
</form>                                             

$("#commentSubmit").submit(function (e) {
    e.preventDefault();
    $.ajax({
        url: "url.to.post",
        type: "POST",
        data: {
            "body": $("#bodyComment").val(),
            "post_id": $("#post_idComment").val()
        }
    });
}
  相关解决方案