【发布时间】:2016-04-24 01:48:15
【问题描述】:
我正在尝试通过 Ajax 发布表单,我遇到了jQuery's POST,这听起来像是要使用的道具工具。我尝试使用以下 html 表单:
<form id="my_form" action="http://localhost:4567/pedidos/guardar" method="POST">
Name:<br>
<input type="text" name="person_name"><br>
Amount:<br>
<input type="text" name="amount">
<br>
<input type="submit" value="Submit" id="submit_form">
</form>
<script type="text/javascript">
$('#submit_form').click( function() {
$.post( 'http://localhost:4567/pedidos/guardar', $('#my_form').serialize(), function(data) {
// ... do something with response from server
alert( "Data saved: " + data );
},
'json' // I expect a JSON response
);
});
</script>
此表单是基于this SO answer构建的
我希望将表单发布到/pedidos/guardar。在服务器端,为了测试表单是否正确发布,我创建了一个非常小的 Sinatra 脚本:
require 'sinatra'
require 'json'
not_found do
status 404
"This page could not be found"
end
get '/' do
"Hello World!"
end
get '/pedidos' do
{ :person_name => "#{params[:person_name]}" }.to_json
end
post '/pedidos/guardar' do
#{}"I got #{params[:person_name]}."
{ :person_name => "#{params[:person_name]}" }.to_json
end
使用我的表单时,我收到了{"person_name":"Juan"},这是 Sinatra 的预期回复。但是我没有收到任何警报窗口,就像根本没有使用 Ajax。
我的表单中缺少什么以使其与 Ajax 一起使用?我需要action 和method="POST" 吗?
提前致谢
【问题讨论】:
-
此表单是否来自:localhost:4567?
-
从表单中移除动作并在jQuery中实现表单的提交功能
$("#myform").submit(function(e){...your code here}); -
您的警报将仅在成功响应时显示,在您的情况下将是
200加上响应中的内容类型将检查 json。您可能希望将您的 ajax 请求从简写post语法转换为更通用的语法 ( api.jquery.com/jQuery.ajax ),以便能够附加将在成功或错误响应时触发的complete回调。然后您可以检查来自服务器的内容。 -
@wapsee 不是,这也是个问题。谢谢大家
标签: javascript jquery ajax forms sinatra