2016-08-27 64 views
1

我有一个表单,当被提交时,页面被重新加载,一个名为#message的div被创建并显示在主体中。我试图ajaxify我的表单,但我坚持如何让信息现在显示而无需重新加载。以下是我的代码如下。在Ajax表单提交后显示DIV结果

$(document).ready(function(){ 
    $('input#submit').on('click', function() { 
    $('#form').submit(function() { 
     $.ajax({ // create an AJAX call... 
     data: $(this).serialize(), // get the form data 
     type: $(this).attr('method'), // GET or POST 
     url: $(this).attr('action'), // the file to call 
     success: function(response) { // on success.. 
     alert($('div#message').text()); // Alert the message text..fails 
     } 
     }); 
     return false; // cancel original event to prevent form submitting 
    }); 
}); 
}); 

<form action="settings.php" method="post" class="standard-form" id="form"> 
     <input type="text" name="email" id="email" value=""> 
     <input type="password" name="pass" id="pass" size="16" value="" class="password-entry" /> 
     <input type="submit" name="submit" value="<?php _e('Update'); ?>" id="submit" class="small button"/> 
</form> 

更新:这是我想要的新功能,但是所有被警告是“[对象] [对象]”,并没有实际的文本。我不确定这意味着什么。

$(document).ready(function(){ 
    $('input#submit').on('click', function() { 
    $('#form').submit(function() { 
     $.ajax({ // create an AJAX call... 
     data: $(this).serialize(), // get the form data 
     type: $(this).attr('method'), // GET or POST 
     url: $(this).attr('action'), // the file to call 
     success: function(data) { // on success.. 
     alert($('div#message').text(data)); 
     } 
     }); 
     return false; // cancel original event to prevent form submitting 
    }); 
}); 
}); 
+0

是什么在你成功的功能“响应”的内容?另外,尝试使用e.preventDefault()来防止默认表单提交。在$(“#form”)提交函数中。 – kinduff

+0

这个html是什么样的?并帮助调试:现在删除您的ajax电话。确保你阻止了默认的表单提交。当你不用重定向就可以点击提交按钮时,你可以添加你的ajax请求。 – Jasen

+0

@Jasen我不确定你是否在考虑他们是否有重定向问题。没有,所以我很抱歉,如果不明确。表单不重定向。提交后,我提醒表单提交后,通常会出现的div的内容,而不是ajax – LearntoExcel

回答

2
$("form").on('submit', function(event) { 
    event.preventDefault(); // to prevent default page reloading 
    var dataString = $(this).serialize(); // to get the form data 

    $.ajax({ 
     type: "POST", 
     url: "post_process.php", 
     data: dataString, 
     success: function(data){ 
      $('form')[0].reset(); // to reset form data 
     } 
    }).done(function(data){ 
     alert(data); // This will be called after the ajax executed 
    }); 

}); 
+0

我试过这个,得到提醒的是“[Object] [object]”。不是信息应该是什么。不确定那是什么意思。 – LearntoExcel

+0

@LearntoExcel请你更新你的HTML,以便我可以给你更合适的答案。 – Naresh

+0

我已经更新了格式html @ e-Designary – LearntoExcel

0

我本来可能误解了你真正想要归档的内容,但我希望是这样。对不起,如果不是。

当我想要显示新的东西而不重新加载时,我正在使用.append()函数,该函数将子元素添加到所选元素。

例如,如果我调用一个数据库ajax(),并希望显示在div中的结果我选择div与jquery和追加结果到div在成功函数。

$('#div').append('<p>Info here</p>') 

这将使一个“p元素”,这是一个孩子的div。而且它会显示不重装 更多.append()这里:http://api.jquery.com/append/

+0

我认为它缺少附加响应:'成功:功能(响应){警报($('div#message').text(response)); }' – kinduff

+0

是的,我认为你是对的。 –

+0

是的,我熟悉append。问题是直到表单提交后才创建div,我试图在ajax调用后显示它。 @kinduff – LearntoExcel