简体   繁体   English

有没有办法使用jQuery和AJAX发布没有任何序列化的表单?

[英]Is there a way to use jQuery and AJAX to post a form without any serialization?

I have a form containing dynamically created checkboxes that filter data to be displayed: 我有一个包含动态创建的复选框的表单,用于过滤要显示的数据:

$html .= "<form id='optionsForm'action='filter.php' method='post'>";
foreach($selectValues as $key => $value){
    $title=new MODEL\String($key);
    $html.= "<fieldset class='optionsBox'>";
    $html.= "<legend>".$title->friendlify()."</legend><br/>";
    foreach($value as $option){
            $html .= "<input type='checkbox' name='".$key."[]' value='$option'>".htmlspecialchars($option)."</input>";
    }
    $html.= "</fieldset>";
}
$html .= "</select><input type='submit' value='submit'></form></div>";

This builds multiple arrays containing the values of the checkboxes, eg 这构建了包含复选框值的多个数组,例如

 name =>
      [0] value1
      [1] value2

 newname =>
      [0] value1
      [1] value2

Once it is submitted the arrays are passed to a php function that breaks them apart and then uses the data to run queries. 提交后,数组将传递给php函数,该函数将它们分开,然后使用数据运行查询。

My problem is that when I use a jQuery .ajax function it serializes the data and I can't work with it the way I want. 我的问题是,当我使用jQuery .ajax函数时,它会序列化数据,我无法按照我想要的方式使用它。

What is the easist way to use the same form action I have to process the form but have the results displayed in a div below the checkboxes? 使用我必须处理表单的相同表单操作的简单方法是什么,但结果显示在复选框下方的div中?

I guess the better question is when filter.php which is used in the form action gets the information what is the variable name going to be when it comes from ajax? 我想更好的问题是,当表单动作中使用的filter.php获取信息时,来自ajax的变量名称是什么? right now i just use the _POST variable and set that equal to my new array name. 现在我只使用_POST变量并将其设置为等于我的新数组名称。

$('#optionsForm').submit(function() {

    $.ajax({
        url: this.action,
        type: "POST"
        data: $(this).serialize(),
        // ...
        // add success/complete/error handlers
    });
    return false;

});

.serialize() will format the data just as if it were a standard form submitted with a submit button. .serialize()将格式化数据,就像它是使用提交按钮提交的标准表单一样。

Clicking your submit button will execute this ajax and prevent the default form action. 单击您的提交按钮将执行此ajax并阻止默认的表单操作。

If you don't like the way jQuery serializes the data you can prepare your own payload based on the form values before you POST to the server. 如果您不喜欢jQuery序列化数据的方式,您可以在POST到服务器之前根据表单值准备自己的有效负载。 You should be able to format the data however you wish. 您应该可以根据需要格式化数据。

you can simply use 你可以简单地使用

$.post("test.php?data1=1&data2=2", function(data) {
   alert("Data Loaded: " + data);
 });

and from server side you will need to request each varable 从服务器端,您将需要请求每个可变量

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

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