dongzhansong5785 2013-03-08 19:11
浏览 82
已采纳

JavaScript表单提交不会发送input type = submit的值

I'm using jQuery to, in some cases, automatically submit a form. Here's my code:

$("form [data-autosubmit]").closest("form").submit();

It works, however it doesn't send the name and value of the input type=submit button.

To elaborate, the following code:

<form method="POST">
<input type="text" name="input" value="text they entered">
<input type="submit" name="submit" value="Submit">
</form>

would send the following POSTdata when submitted by the user:

input: text they entered
submit: Submit

However when the form is submitted by JavaScript, only this POSTdata is sent:

input: text they entered

My PHP scripts rely on the presence of a "submit" value in the POSTdata.

I was thinking I could do:

$("form [data-autosubmit]").closest("form").find("input[type=submit]").click();

But it seems to defy logic, when there is a submit event on the form intended for this purpose.

  • 写回答

1条回答 默认 最新

  • dsv73806 2013-03-08 19:15
    关注

    HTML forms were built to support multiple submit inputs (so the same form could have an "Insert" and "Edit" button, for instance). Therefore the form relies on the click to actually register the chosen field in the _POST submission. Basically, HTML allows a form that looks like this:

    <form [...]>
      <input type="submit" name="Insert" value="Insert">
      <input type="submit" name="Update" value="Update">
    </form>
    

    to be handled like this on the server-side:

    if(!empty($_REQUEST['Update'])){
      //Run update logic here..
    }
    elseif(!empty($_REQUEST['Insert'])){
      //Run insert logic here...
    }
    

    If the Javascript submit() function registered both buttons in the POST array it would break applications using this valid markup/logic, so they default to omitting submit inputs.

    So your Javascript workaround (triggering a click on the submit button rather than just submit()ing the form) is the correct approach.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写