mootools将表单变成json格式 【转】

来源:互联网 发布:淘宝新品打标时间 编辑:程序博客网 时间:2024/06/07 19:53

JSON 是个好东西,但我却因为一个小问题困扰了好久!

假设通过 Ajax 调用从服务器获得这样一个 JSON 字符串:

  1. {"username":"dualface","email":"ddddd@ddddd.com"}

知道怎么在 JavaScript 里面转换为对象吗?

正确的做法是:

  1. obj = eval("(" + json_string + ")");

这么重要的问题,在 JSON.org 上居然没放在首页,而是放在 http://www.json.org/js.html

解决了小毛病,一会儿又遇到个大问题:

  1. <form>
  2. <input type="text" name="roles[]" value=“1” />
  3. <input type="text" name="roles[]" value=“2” />
  4. <input type="text" name="roles[]" value=“3” />
  5. <input type="text" name="roles[]" value=“4” />
  6. </form>

这种表单如果直接提交给 PHP,那么 $_POST[’roles’] 将会是一个数组,包含有 1/2/3/4 这些值。
这个特性是很方便的,但将表单转换为 JSON 来提交时,就比较麻烦了。

我用的 js 库是 mootools,它提供的 form.toQueryString() 不能处理这种情况,Json.toString() 也不行。
在网上搜索一番后,发现 jquery、prototype 都不支持(可能是我没看到)。

只好自己写了一个:

  1. function formToJSON(form)
  2. {
  3.     json = '{';
  4.     isarray = false;
  5.     for (i = 0max = form.elements.lengthi < maxi++) {
  6.         e = form.elements[i];
  7.         name = e.name;
  8.         if (name.substring(name.length - 2) == '[]') {
  9.             name = name.substring(0name.length - 2);
  10.             lastarr = name;
  11.             if (isarray == false) {
  12.                 json += '"' + name + '":[';
  13.             }
  14.             isarray = true;
  15.         } else {
  16.             if (isarray) {
  17.                 json = json.substring(0json.length - 1) + '],';
  18.             }
  19.             isarray = false;
  20.         }
  21.        
  22.         switch (e.type) {
  23.         case 'checkbox':
  24.         case 'radio':
  25.             if (!e.checked) { break}
  26.         case 'hidden':
  27.         case 'password':
  28.         case 'text':
  29.             if (!isarray) {
  30.                 json += '"' + name + '":';
  31.             }
  32.             json += '"' + e.value.replace(new RegExp('(["////])''g')'//$1') + '",';
  33.             break;
  34.         case 'button':
  35.         case 'file':
  36.         case 'image':
  37.         case 'reset':
  38.         case 'submit':
  39.         default:
  40.         }
  41.     };
  42.    
  43.     return json.substring(0json.length - 1) + '}';
  44. }

使用很简单:

  1. json_string = formToJSON(document.forms["myform"]);
  2. // 用 mootools 的 ajax 提交
  3. new Ajax('test.php'{
  4.     postBody'json=' + encodeURIComponent(json_string),
  5.     onCompleteafterDataFormSubmit
  6. }).request();

test.php 收到后:

  1. <?php
  2. $json = $_POST['json'];
  3. // 使用 PHP 5.2 的 json_decode() 解析
  4. $arr = json_decode($jsontrue);
  5. print_r($arr);
  6. // 使用 PEAR::Services_JSON 解析
  7. $services = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
  8. $arr = $services->decode($json);
  9. print_r($arr);

这里解析都是强制解析为 php 的数组。一是这样方便使用,二是嵌套的数据可以解析出来。

原创粉丝点击