【问题标题】:Adding variable to ajax post in vanilla javascript在香草javascript中将变量添加到ajax帖子
【发布时间】:2017-10-23 16:23:41
【问题描述】:

我在 vanilla javascript 中收到了 post ajax 请求,一切正常,但我需要向form_data 添加一个变量,该变量将发送到 php。 例如变量apple = 1 已经在form_data 中。我需要添加orange = 2,但我无法在我的html 表单中添加。我的js代码如下:

function button_publish_ajax(variable){
    var form = document.getElementById("form-buttons");
    var form_data = new FormData(form);
        for ([key,value] of form_data.entries()){
        console.log(key + ': '+value);
        }
    var action = form.getAttribute("action");                   
    var xhr = new XMLHttpRequest();
    xhr.open('POST', action, true);
    xhr.overrideMimeType('text/xml; charset=UTF-8');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.onreadystatechange = function (){
    if (xhr.readyState == 4 && xhr.status == 200){
        var result = xhr.responseText;
        console.log("Result:" + result);
    }
    };
    xhr.send(form_data);
   }

总结一下:我想在form_data中添加orange=1。有人知道该怎么做吗? 我的主要目的是添加信息单击哪个按钮来区分 php.ini 中的 ajax 函数。我的 HTML 代码如下:

 <form method="post" action="cms_offers_button.php" id="form-buttons">
  <input type="hidden" name="offer_list" value="12">
    <input name="PublishListItem" type="button" class="btn btn-info offer-publish" value="Publish" id="publish-12" style="display: none;"/>
    <input name="WithdrawListItem" type="button" class="btn btn-info offer-withdraw" value="Withdraw" id="withdraw-12"/>
    <input name="EditListItem" type="button" class="btn btn-default offer-edit" value="Edit" id="edit-12" />
    <input name="DeleteListItem" type="button" class="btn btn-danger offer-delete" value="Delete" id="delete-12"/>

【问题讨论】:

    标签: javascript ajax


    【解决方案1】:

    使用 append() 函数添加它,例如:

    //form_data.append(name, value);
    
    form_data.append('orange',2);
    

    希望这会有所帮助。

    【讨论】:

    • 附加表单数据是否比使用隐藏输入字段更好?他们似乎都做同样的事情。隐藏输入字段:stackoverflow.com/questions/7324950/…
    • 视情况而定。如果该值将静态添加或从服务器端传递
    • 我使用了隐藏的输入字段,但在这种情况下我不能使用它们。我有一个表单,它有 3 个按钮:“发布”、“删除”、“显示”,我需要在 js 函数中区分每个按钮的 ajax 操作
    • 请将 HTML 代码添加到问题中,并尝试描述更多您想要传递的值..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2012-09-23
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多