【问题标题】:Send html array as post variable using Request.JSON使用 Request.JSON 将 html 数组作为 post 变量发送
【发布时间】:2010-05-18 02:05:59
【问题描述】:

我有一个 html:

First name: <input type='text' name='first_name' value='' /><br/>
Last name: <input type='text' name='last_name' value='' /><br/>
<input type='checkbox' name='category[]' value='Math' /> Math<br/>
<input type='checkbox' name='category[]' value='Science' /> Science<br/>
<input type='checkbox' name='category[]' value='History' /> History<br/>
etc.....

我想通过 mootools ajax 发送(使用 post 方法)选定的类别(category[]),这样如果我将 $_POST 变量转储到服务器中,我会得到类似的结果:

array(1) {
   [category]=>
    array(2) {
    [0]=>
    string(4) "Math"
    [1]=>
    string(7) "History"
  }
}

它的 javascript(mootools) 代码应该是什么?下面是我的部分代码。

new Request.JSON({url: '/ajax_url',
            onSuccess: function(){
                alert('success');
            }
        }).post(???);

请注意,我不想发送 first_name 和 last_name 字段。我只想发送一个 html 数组的类别字段。

【问题讨论】:

    标签: javascript ajax arrays json mootools


    【解决方案1】:

    您只需要序列化字段:

    var theForm = $('form-id');
    
    new Request.JSON({url: '/ajax_url',
        onSuccess: function(){
            alert('success');
        }
    }).post(theForm.toQueryString()); // this will create the GET-style query
    

    【讨论】:

      【解决方案2】:

      这是一种方法:

      $("formid").addEvent("submit", function(e) {
          e.stop();
          var x = {};
          this.toQueryString().split('&').each(function(i) {
              var p = i.split('=');
              if (p[0].contains("[]")) {
                  p[0] = p[0].replace("[]", "");
                  if ($type(x[p[0]]) != "array")
                      x[p[0]] = [];
                  x[p[0]].push(p[1]);
              }
              else {
                  x[p[0]] = p[1];
              }
      
          });
          // return a number of formats, depends on your backend:
          console.log(x, JSON.encode(x), $H(x).toQueryString());
      });
      

      这可以输出:

      对象(x)或...

      json {"first_name":"Dimitar","last_name":"Christoff","category":["Math","Science"]} 或者...

      查询字符串:first_name=Dimitar&amp;last_name=Christoff&amp;category[0]=Math&amp;category[1]=Science

      祝你好运。案例:http://www.jsfiddle.net/dimitar/Wxx3b/1/

      附言您不打算使用name[] 作为字段名称,这确实是PHP 处理事物的快捷方式/好方法,但不适用于客户端imo。

      【讨论】:

        【解决方案3】:

        我会从 Prototype JS 库中检查这个函数的源代码,看看它是如何工作的:http://github.com/sstephenson/prototype/blob/master/src/dom/form.js#L100 的第 100 行

        接受category[] 格式可能需要稍作调整,但这是一个开始或灵感。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-05-27
          • 1970-01-01
          • 2023-03-12
          • 2013-04-07
          • 1970-01-01
          • 1970-01-01
          • 2011-03-01
          • 1970-01-01
          相关资源
          最近更新 更多