Jquery onchange选择向PHP提交表单

时间:2012-05-01 12:56:22

标签: jquery

我没有真正向您展示的代码,但是我要说我有一个包含3个HIDDEN字段的表单,其中包含日期,城市和地址。 我也有一个选择有3个选项(比如苹果,微软和谷歌)。

我想要的是当用户将select更改为其他选项时,jquery应该将selectbox + 3个隐藏字段的值发送到PHP页面,比如proces.php。 Proces.php处理mysql_query等,它不返回任何内容。

有人能告诉我这是怎么做到的吗?我不希望有人为我编写完整的脚本,因为我没有提供任何HTML代码,只是大纲,或者可能是教程或其他内容的链接。

4 个答案:

答案 0 :(得分:7)

首先,您的表单应如下所示:

<form action="process.php" method="post" id="myForm">
    <select name="site" id="site">
        <option>Apple</option>
        <option>Google</option>
        <option>Microsoft</option>
    </select>
    <input type="hidden" name="date" value="01/05/2012" />
    <input type="hidden" name="city" value="London" />
    <input type="hidden" name="address" value="[... address ...]" />
</form>

然后通过AJAX提交,您将使用serialize()方法收集表单数据:

$("#site").on("change", function() {
    var $form = $("#myForm");
    var method = $form.attr("method") ? $form.attr("method").toUpperCase() : "GET";
    $.ajax({
        url: $form.attr("action"),
        data: $form.serialize(),
        type: method,
        success: function() {
            // do stuff with the result, if you want to 
        }
    });
});

或者,如果您不想使用AJAX,只需提交标准表单,您可以触发表单提交,如下所示:

$("#site").on("change", function() {
    $("#myForm").submit();
});

答案 1 :(得分:1)

如果你想使用jquery发送表单,可以使用Jquery Form插件&lt;
http://jquery.malsup.com/form/ 所以你基本上可以做的是使用

$(document).ready(function(){
$('form selector').ajaxForm(opts);
//u can define the opt urself itz easy look at the link
$("selects selector").change(function(){
$(form selector).ajaxSubmit(function(){//something you wanna do if form is submitted successfully})
});
});

答案 2 :(得分:1)

让我们看看,这是一个表单,并在下拉选项更改时提交了吗? 你真的不需要使用AJAX。 你可以像这样使用jquery .change()方法:

$('.mydropdown').change(function() {
  // Also do some checking to see if the values are not empty 
  // and then submit the form using:
  $('#myform').submit();
});

在php文件中,您可以使用$ _POST变量获取它们。

答案 3 :(得分:1)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="#">
    <label for="brand">Brand</label>
    <select name="brand" id="brand">
        <option>Apple</option>
        <option>Microsoft</option>
        <option>Google</option>     
    </select>
    <input type="hidden" name="date" id="date" value="7/4/1776" />
    <input type="hidden" name="city" id="city" value="My City"  />
    <input type="hidden" name="address" id="address" value="123 Fake Street" />
</form>
<script type="text/javascript" src='//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type="text/javascript">
    $('#brand').on('change',function() {
        $.post("process.php", $("#form1").serialize());
    });
</script>
</body>
</html>
相关问题