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.

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料