如何缩短通过xmlhttp发送的帖子表格?

时间:2014-09-09 07:32:43

标签: javascript forms post xmlhttprequest

到目前为止,我有这个表单在评论下方点击提交upvote。我已经把它作为伪代码,所以它避免了过于局部化的问题:

<form id="upvote" method=post action="/comment_upvote">

    <input type="hidden" name="cid" value=%cid></input>
    <input type="hidden" name="bpid" value=%bpid></input>
    ...
    <input type="submit" value="">

</form>

和这个Javascript xmlhttp代码来处理它

var upvote = document.getElementById("upvote");

        upvote.onclick = function(event) {
            event.preventDefault();
            xmlhttp=new XMLHttpRequest();
            xmlhttp.open("POST", "http://localhost/comment_upvote", true)
            xmlhttp.send()
        }

我觉得这不是最好的方式,尤其是谈论使用完整的POST表单处理upvote。

我的问题是:POST这个upvote表单有什么更好,更易读的方式?

3 个答案:

答案 0 :(得分:0)

就像你现在做的那样好..但是Javascript错了,因为你没有将POST变量传递给xmlhttp.send()

var upvote = document.getElementById("upvote");

        upvote.onclick = function(event) {
            event.preventDefault();
            xmlhttp=new XMLHttpRequest();
            xmlhttp.open("POST", "http://localhost/comment_upvote", true)
            xmlhttp.send()
        }

应该是

var upvote = document.getElementById("upvote");
var data_f = new FormData(upvote); // copy html form content to data_f var

        upvote.onclick = function(event) {
            event.preventDefault();
            xmlhttp=new XMLHttpRequest();
            xmlhttp.open("POST", "http://localhost/comment_upvote", true)
            xmlhttp.send(data_f) // send form with variables
        }

答案 1 :(得分:-1)

Jquery可能是您正在寻找的框架。 它讨论了http请求以及DOM操作和许多其他东西。看看这个: http://api.jquery.com/

你想做的事情可以用jQuery完成,就像这样:

jQuery.post("http://localhost/comment_upvote" ,{cid:%cid,bpid:%bpid} );

假设服务器在JavaScript代码中正确打印%cid和%bpid。

不要忘记将jquery库添加到你的html:)

答案 2 :(得分:-1)

如果你真的不想使用框架(没有羞耻),这里有一些事情要做(并且不需要对一些数据使用post方法)

// Resuable crossbrowser XMLHttpRequest (Wikipedia)
if (typeof XMLHttpRequest === "undefined") {
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
    catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
    catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) {}
    throw new Error("This browser does not support XMLHttpRequest.");
  };
}

// Resuable crossbrowser event listener manager (stackoverflow)
function addListener(elt, type, listener, useCapture) {
    if (window.addEventListener) {
        elt.addEventListener(type, listener, useCapture);
    } else if (window.attachEvent) {
        elt.attachEvent('on' + type, listener);
    }
}

// Resuable serialize-as-query-string function (w3school and myself)
function serialize(additionalParams) {
  var str = additionalParams || [];
  for (var i=0; i<this.length; i++) {
      var elt = this.elements[i],
          add = true;
      if ((elt.type == 'checkbox' || elt.type == 'radio') && !elt.checked) {
          add = false;
      }
      add && str.push(encodeURIComponent(elt.name) + "=" + encodeURIComponent(elt.value));
  }
  return str.join("&");
}

// Reusable submit handler
function sendXhr(e) {
    var form = e.target || e.srcElement;
    e = e || window.event;
    e.preventDefault();
    var serializedForm = serialize.call(form, additionalParams);
    debug.innerHTML = serializedForm;
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        var done = this.done || 4;
        if (this.readyState === done){
            alert('XHR done, and got response!');
        }
    };
    request.open('GET', form.action + '?' + serializedForm, true);
    request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    request.send(null);
}

// Code for this page    
var form = document.getElementById('upvote');

var additionalParams = ['foo=bar', 'sam=OK']; // Completely optional

addListener(form, 'submit', sendXhr);

N.B。 :不要使用HTMLElement.onclick

在此处查看演示:http://jsfiddle.net/8txdhxtz/