【问题标题】:How to shorten a post form sent through xmlhttp?如何缩短通过 xmlhttp 发送的 post 表单?
【发布时间】:2014-11-02 13:02:03
【问题描述】:

到目前为止,当在评论下方单击此表单时,我可以提交支持。我已尽可能将其设为伪代码,以避免过于本地化的问题:

<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 表单来处理投票时。

我的问题是:有什么更好、更易读的方式来发布这个投票表单?

【问题讨论】:

    标签: javascript forms post xmlhttprequest


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 抱歉,我需要本机 Javascript 来处理这个用例,但请 +1,因为这对其他人来说就足够了 :-)
    • 怎么来的?我认为没有更好的方法:)
    • jQuery “更好”是非常主观的,但没有什么不是原生 JavaScript。
    【解决方案2】:

    如果你真的不想使用框架(这并不丢人),可以从这里开始(并且不需要对一些数据使用 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);
    

    注意: 不要使用 HTMLElement.onclick

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

    【讨论】:

      【解决方案3】:

      就像你现在做的那样很好。但是 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
              }
      

      【讨论】:

        猜你喜欢
        • 2011-10-22
        • 1970-01-01
        • 2016-03-11
        • 1970-01-01
        • 2015-07-29
        • 1970-01-01
        • 1970-01-01
        • 2020-09-03
        • 1970-01-01
        相关资源
        最近更新 更多