简体   繁体   English

在vanilla javascript中将变量添加到ajax帖子

[英]Adding variable to ajax post in vanilla javascript

I've got post ajax request in vanilla javascript, all works well, but I need to add an variable to form_data , which will be send to php. 我已经在vanilla javascript中发布了ajax请求,一切正常,但我需要向form_data添加一个变量,它将被发送到php。 For example variable apple = 1 is already in form_data. 例如,变量apple = 1已经在form_data中。 I need to add orange = 2 , but I can't do it in my html form. 我需要添加orange = 2 ,但我不能用我的html格式。 My js code is below: 我的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);
   }

To sum up: I want to add orange=1 to form_data. 总结一下:我想在form_data中添加orange=1 Anyone knows how to do it? 谁知道怎么做? My primary intention was to add information which button was clicked to differentiate ajax functions in php. 我的主要目的是添加点击按钮的信息,以区分php中的ajax函数。 My HTML code is below: 我的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"/>

Add it using append() function like: 使用append()函数添加它,如:

//form_data.append(name, value);

form_data.append('orange',2);

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM