28

アプリケーション (私の大学のソーシャル ネットワークのようなもの) を開発しています。コメントを追加する必要があります (特定のデータベースに行を挿入します)。これを行うには、HTML ページにさまざまなフィールドを持つ HTML フォームを用意します。送信時にはフォームのアクションは使用しませんが、フォームを送信する前にカスタム JavaScript 関数を使用してデータを作成します。

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を使用したいのですが、フォームの入力値をキャッチする方法がわからないため、これを行う方法がわかりません。誰でも私を助けることができますか?

4

9 に答える 9

33

(OPの要求に従って)実際に純粋なjavascript答えを出した人はいないので、次のとおりです。

function postAsync(url2get, sendstr)    {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    if (req != undefined) {
        // req.overrideMimeType("application/json"); // if request result is JSON
        try {
            req.open("POST", url2get, false); // 3rd param is whether "async"
            }
        catch(err) {
            alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
            return false;
            }
        req.send(sendstr); // param string only used for POST

        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200)  // only if "OK"
                { return req.responseText ; }
            else    { return "XHR error: " + req.status +" "+req.statusText; }
            }
        }
    alert("req for getAsync is undefined");
}

var var_str = "var1=" + var1  + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
    // hint: encodeURIComponent()

if (ret.match(/^XHR error/)) {
    console.log(ret);
    return;
    }

あなたの場合:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;
于 2016-11-23T07:39:13.330 に答える
10

送信ボタンに onclick 関数を追加できますが、Enter キーを押して関数を送信することはできません。私の場合、これを使用します:

<form action="" method="post" onsubmit="your_ajax_function(); return false;">
    Your Name <br/>
    <input type="text" name="name" id="name" />
    <br/>
    <input type="submit" id="submit" value="Submit" />
</form>

それが役に立てば幸い。

于 2014-03-21T20:43:24.200 に答える
4

これは大学のタスクであり、コードを保存する必要がないため、jQueryを使用する方がはるかに簡単です。

したがって、コードは次のようになります。

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) { ... },
    });

}
于 2012-11-28T20:41:08.383 に答える
2

このタイプの要件にはjqueryを使用することをお勧めします。これを試してみてください

<div id="commentList"></div>
<div id="addCommentContainer">
    <p>Add a Comment</p> <br/> <br/>
    <form id="addCommentForm" method="post" action="">
        <div>
            Your Name <br/>
            <input type="text" name="name" id="name" />


            <br/> <br/>
            Comment Body <br/>
            <textarea name="body" id="body" cols="20" rows="5"></textarea>

            <input type="submit" id="submit" value="Submit" />
        </div>
    </form>
</div>​

$(document).ready(function(){
    /* The following code is executed once the DOM is loaded */

    /* This flag will prevent multiple comment submits: */
    var working = false;
    $("#submit").click(function(){
    $.ajax({
         type: 'POST',
         url: "mysubmitpage.php",
         data: $('#addCommentForm').serialize(), 
         success: function(response) {
            alert("Submitted comment"); 
             $("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
         },
        error: function() {
             //$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
            alert("There was an error submitting comment");
        }
     });
});
});​
于 2012-11-28T20:55:29.527 に答える
0

最近では、プレーンな 'ol JS を使用してこれを実現する方がはるかに簡単です。

const form = document.querySelector('#your-form'),
      data = new URLSearchParams();
for (const pair of new FormData(form)) {
    data.append(pair[0], pair[1]);
}

fetch(form.action, {
    method: form.method || 'POST',
    body: data,
}).then(response => response.json())  //  or .text()
.then(data => {
    console.log('SUBMITTED', data);
});
于 2021-11-26T20:47:06.877 に答える