submit the form using ajax

后端 未结 8 882
栀梦
栀梦 2020-12-05 10:17

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

8条回答
  •  一生所求
    2020-12-05 10:53

    Nobody has actually given a pure javascript answer (as requested by OP), so here it is:

    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;
        }
    

    In your case:

    var var_str = "video_time=" + document.getElementById('video_time').value 
         + "&video_id=" + document.getElementById('video_id').value;
    

提交回复
热议问题