Javascript 使用javascript通过函数调用模拟post表单提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30421830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:09:32  来源:igfitidea点击:

Simulate post form submit with a function call with javascript

javascriptjqueryajaxforms

提问by Alfred Huang

With jQuery, we can simulate submitting a form:

使用 jQuery,我们可以模拟提交表单:

<form id="form1" method="post">
    <input name="key1" value="value1" />
    <input name="key2" value="value2" />
</form>

With an AJAX function call:

使用 AJAX 函数调用:

$.post('', { key1: 'value1', key2: 'value2' }, function() {
   // do call back
});

If we use jquery.form.js

如果我们使用 jquery.form.js

$('#form1').ajaxSubmit({
    success: function() {
        // do call back
    }
});


Ok, now comes my question:

好的,现在我的问题来了:

I don't have the form in the markup and I want to submit a form with some dynamic content using the method 'POST'.

我没有标记中的表单,我想使用“POST”方法提交一个包含一些动态内容的表单。

I want to make a function call to simulate the procedure, maybe something like:

我想进行函数调用来模拟该过程,可能类似于:

utils.post('/url', {key1: 'value1', key2: 'value2'});

After that call, the effect is just the same as the form I have above and I submit it, with a natural synchronized way.

调用之后,效果和我上面的表单一样,我提交了,自然同步。

Is there a nice way to do this?

有没有很好的方法来做到这一点?



If the problem is not clear, I can make an ugly example to explain what I want:

如果问题不清楚,我可以举一个丑陋的例子来解释我想要的:

util.post = function(url, fields) {
    var $form = $('<form action="'+url+'" method="post"></form>');
    var key, val;
    for(key in fields) {
        if(fields.hasOwnProperty(key)) {
            val = fields[key];
            $form.append('<input type="hidden" name="'+key+'" value="'+val+'" />');
        }
    }
    $form.submit();
}

The above method works but I think it is not nice enough. When the fields have a special character or something else it may cause an error.

上述方法有效,但我认为它不够好。当字段具有特殊字符或其他内容时,可能会导致错误。

回答by Barmar

You can use jQuery to construct the form functionally, rather than by concatenating strings, so special characters won't be a problem.

您可以使用 jQuery 从功能上构建表单,而不是通过连接字符串,因此特殊字符不会成为问题。

You will need to attach this form to the HTML bodybefore submitting it; recent versions of Chrome now require this.

body在提交之前,您需要将此表单附加到 HTML 中;最新版本的 Chrome现在需要这个

var util = {};
util.post = function(url, fields) {
    var $form = $('<form>', {
        action: url,
        method: 'post'
    });
    $.each(fields, function(key, val) {
         $('<input>').attr({
             type: "hidden",
             name: key,
             value: val
         }).appendTo($form);
    });
    $form.appendTo('body').submit();
}

回答by Brian M. Hunt

Since the accepted answer may no longer work in e.g. Chromium based browsersin some circumstances, here's a workaround:

由于在某些情况下接受的答案可能不再适用于基于 Chromium 的浏览器,这里有一个解决方法:

util.post = function(url, fields) {
  var $form = $('<form>', {
    action: url,
    method: 'post'
  }).append(
    $.map(fields, function(key, val) {
      return $('<input>').attr({
         type: "hidden",
         name: key,
         value: val
      }).appendTo($form);
    })
  )
  var w = window.open("about:blank")
  w.document.write($form[0].outerHTML)
  w.document.forms[0].submit()
}

回答by Lelio Faieta

Your only problem is that since you don't have form fields to get data from you can't use .serialize to build the array. You just have to build the array manually.

您唯一的问题是,由于您没有可从中获取数据的表单字段,因此您无法使用 .serialize 来构建数组。您只需要手动构建阵列。

Key1...Keyn can be names you assign instead of form fields name attributes (that is what actually serialize do) and values can be whatever you want:

Key1...Keyn 可以是您分配的名称,而不是表单字段名称属性(实际上是序列化所做的),值可以是您想要的任何值:

  • html from a div;
  • values calculated by you;
  • javascript variables;
  • values coming from db;
  • 来自 div 的 html;
  • 您计算的值;
  • javascript变量;
  • 来自 db 的值;

The point is that you are not simulating posting a form in any case. With ajax you are just making it asyncronousand this helps you because you don't need to change/reload the page to elaborate the form results.

关键是您在任何情况下都没有模拟发布表单。使用 ajax,你只是让它异步,这对你有帮助,因为你不需要更改/重新加载页面来详细说明表单结果。