简体   繁体   English

JavaScript - 表单OnSubmit可以使用,但Action不可以

[英]JavaScript - Form OnSubmit works but Action doesn't

On my FORM , for some reason, I can get my form input variable via onsubmit but not using action . 在我的FORM ,出于某种原因,我可以通过onsubmit获取我的表单输入变量但不使用action

This works: 这有效:

<form onsubmit="javascript:myFunc(this.city.value);">
    <p><input type="text" id="city-field" name="city" onfocus="this.select();" /> <input type="submit" value="Find" /></p>
</form>

This doesn't work ( this.city.value is found to be null) 这不起作用(发现this.city.value为null)

<form action="javascript:myFunc(this.city.value);">
    <p><input type="text" id="city-field" name="city" onfocus="this.select();" /> <input type="submit" value="Find" /></p>
</form>

Why is it that onsubmit can get the this.city.value but the action event cannot? 为什么onsubmit可以获得this.city.value但是action事件不能?

The form action tag doesn't reference anything with this 表单动作标签不与任何引用this

Instead, use an absolute location 相反,使用绝对位置

action="javascript:myFnc(document.getElementById('city-field').value)"

Edit : Thanks to Christoph's comment, below, I realized my huge oversight. 编辑 :感谢克里斯托夫的评论,下面,我意识到我的巨大疏忽。 Here is the final solution with his suggestion implemented. 这是他的建议实施的最终解决方案。

<form action="" onsubmit="myFunc(this.city.value); return false;">
    <p><input type="text" id="city-field" name="city" onfocus="this.select();" /> <input type="submit" value="Find" /></p>
</form>

This should do what you need. 这应该做你需要的。 I apologize for not giving you my full attention in my previous responses. 我很抱歉在之前的回复中没有全神贯注。

HTML forms are used for submitting data back to a script on the server for data processing. HTML表单用于将数据提交回服务器上的脚本以进行数据处理。 When a form is submitted, the data in the form fields is passed to the server in the form of name-value pairs. 提交表单时,表单字段中的数据将以名称 - 值对的形式传递给服务器。 Server-side scripts, which can be written in several different languages, are used to process the incoming data and return a new HTML page to the browser. 服务器端脚本可以用几种不同的语言编写,用于处理传入的数据并将新的HTML页面返回给浏览器。 The page returned to the browser could be anything from a "Thank you for registering" message or a list of search results generated from a database query. 返回浏览器的页面可以是“感谢您注册”消息或从数据库查询生成的搜索结果列表。

since form is for sending data to another file on the server. 因为表单用于将数据发送到服务器上的另一个文件。 in action we can only specify the path to which we need to send the data. 在行动中,我们只能指定我们需要发送数据的路径。 so there you cant get the values which the form is having. 所以你不能得到表格所具有的价值。

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

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