提交使用AJAX的形式 [英] submit the form using ajax

查看:94
本文介绍了提交使用AJAX的形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个应用程序(一种社会网络,为我的大学)。我需要添加评论(在特定数据库中插入一行)。要做到这一点,我在各个领域我的HTML页面的HTML表单。在提交的时候,我不使用形式的行动,但我使用自定义JavaScript函数提交表单之前制定的一些数据。

I'm developing an application (a kind of social network for my university). I need to add a comment (insert a row in a specific database). To do this, I have a HTML form in my html page with various fields. At time of submit I don't use the action of form but i use a custom javascript function to elaborate some data before submitting form.

function sendMyComment() {

    var oForm = document.forms['addComment'];
    var input_video_id = document.createElement("input");
    var input_video_time = document.createElement("input");

    input_video_id.setAttribute("type", "hidden");
    input_video_id.setAttribute("name", "video_id");
    input_video_id.setAttribute("id", "video_id");
    input_video_id.setAttribute("value", document.getElementById('video_id').innerHTML);

    input_video_time.setAttribute("type", "hidden");
    input_video_time.setAttribute("name", "video_time");
    input_video_time.setAttribute("id", "video_time");
    input_video_time.setAttribute("value", document.getElementById('time').innerHTML);

    oForm.appendChild(input_video_id);
    oForm.appendChild(input_video_time);

    document.forms['addComment'].submit();
}

最后一行将表单提交到正确的页面。它工作正常。但我想用ajax提交表单,我不知道如何做到这一点,因为我不知道如何捕捉到表单输入值。任何人都可以帮我吗?

The last line submits the form to the correct page. It works fine. But I'd like to use ajax for submitting the form and I have no idea how to do this because I have no idea how to catch the form input values. anyone can help me?

推荐答案

这是很容易,只需使用 jQuery的,因为这是大学只是一个任务,你不需要保存code。

It's much easier to just use jQuery, since this is just a task for university and you do not need to save code.

那么,你的code将是这样的:

So, your code will look like:

function sendMyComment() {
    $('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
    $.ajax({
        type: 'POST',
        url: $('#addComment').attr('action'),
        data: $('form').serialize(), 
        success: function(response) { ... },
    });

}

这篇关于提交使用AJAX的形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆