【问题标题】:Passing data through a jQuery .post() function通过 jQuery .post() 函数传递数据
【发布时间】:2012-11-13 19:43:15
【问题描述】:

我通常像这样通过 .post() 传递数据:

 $.post(
    "/ajax.php",
    $("#form").serialize(),
    function(responseJSON) {
        console.log(responseJSON);
    },
    "html"
);

在我的表单"#form" 中,我通常有一个名为“id”的隐藏输入,其中包含我要运行查询的项目的 id 的值。

我想要做的是取出隐藏的输入并在我的提交按钮中添加data-id="$id" 属性,并让jQuery 函数从那里提取数据并将其与其他#form 字段一起发送。

简单来说,我要问的是如何将$('#form').serialize()$('#button').data('id') 一起传递到我的后端,并在一个$.post() 函数中实现?

【问题讨论】:

    标签: jquery post


    【解决方案1】:

    试试这个

    var data = $("#form").serialize() + '&data-id=' + $('#button').data('id');
    $.post(
        "/ajax.php",
        data,
        function(responseJSON) {
            console.log(responseJSON);
        },
        "html"
    );
    

    【讨论】:

      【解决方案2】:

      .serialize() 只是用数据创建一个字符串。您只需将&<variable>=<value> 附加到末尾即可。

      【讨论】:

        【解决方案3】:

        您可以尝试使用 http://phery-php-ajax.net/ 自动为您执行此操作的库,您无需担心内部工作原理

        Phery::instance()->set(array(
           'function' => function($data){ 
               // $data['id'] = the hidden in your form
               return PheryResponse::factory()->json($your_array_that_will_be_turned_to_json);
           }
        ))->process();
        
        <form data-remote="function" method="POST">
          <input type="hidden" name="id">
        </form>
        

        在您的 Javascript 中,您可以处理 JSON

        $(function(){
          $('form').bind('phery:json', function(event, json_data){
            // deal with your json_data
          }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-02
          • 2014-04-30
          • 1970-01-01
          • 2022-01-21
          相关资源
          最近更新 更多