使用javascript通过函数调用模拟帖子表单提交

时间:2022-03-24 01:56:58

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.

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

3 个解决方案

#1


22  

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 body before submitting it; recent versions of Chrome now require this.

在提交之前,您需要将此表单附加到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();
}

#2


0  

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;
  • 来自div的html;
  • values calculated by you;
  • 你计算的价值;
  • javascript variables;
  • javascript变量;
  • values coming from db;
  • 来自db的值;

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

关键是你在任何情况下都没有模拟发布表格。使用ajax,您只是将其设置为异步,这对您有所帮助,因为您无需更改/重新加载页面以详细说明表单结果。

#3


0  

Since the accepted answer may no longer work in e.g. Chromium based browsers in 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()
}

#1


22  

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 body before submitting it; recent versions of Chrome now require this.

在提交之前,您需要将此表单附加到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();
}

#2


0  

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;
  • 来自div的html;
  • values calculated by you;
  • 你计算的价值;
  • javascript variables;
  • javascript变量;
  • values coming from db;
  • 来自db的值;

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

关键是你在任何情况下都没有模拟发布表格。使用ajax,您只是将其设置为异步,这对您有所帮助,因为您无需更改/重新加载页面以详细说明表单结果。

#3


0  

Since the accepted answer may no longer work in e.g. Chromium based browsers in 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()
}