mootools将表单变成json格式(三)
时间:2007-08-12 来源:linxh
本文转自: http://www.dualface.com/blog/?p=372
原文如下:
JSON 是个好东西,但我却因为一个小问题困扰了好久!
假设通过 Ajax 调用从服务器获得这样一个 JSON 字符串:
- {"username":"dualface","email":"[email protected]"}
知道怎么在 JavaScript 里面转换为对象吗?
正确的做法是:
- obj = eval("(" + json_string + ")");
这么重要的问题,在 JSON.org 上居然没放在首页,而是放在 http://www.json.org/js.html。
解决了小毛病,一会儿又遇到个大问题:
- <form>
- <input type="text" name="roles[]" value=“1” />
- <input type="text" name="roles[]" value=“2” />
- <input type="text" name="roles[]" value=“3” />
- <input type="text" name="roles[]" value=“4” />
- </form>
这种表单如果直接提交给 PHP,那么 $_POST[’roles’] 将会是一个数组,包含有 1/2/3/4 这些值。
这个特性是很方便的,但将表单转换为 JSON 来提交时,就比较麻烦了。
我用的 js 库是 mootools,它提供的 form.toQueryString() 不能处理这种情况,Json.toString() 也不行。
在网上搜索一番后,发现 jquery、prototype 都不支持(可能是我没看到)。
只好自己写了一个:
- function formToJSON(form)
- {
- json = '{';
- isarray = false;
- for (i = 0, max = form.elements.length; i < max; i++) {
- e = form.elements[i];
- name = e.name;
- if (name.substring(name.length - 2) == '[]') {
- name = name.substring(0, name.length - 2);
- lastarr = name;
- if (isarray == false) {
- json += '"' + name + '":[';
- }
- isarray = true;
- } else {
- if (isarray) {
- json = json.substring(0, json.length - 1) + '],';
- }
- isarray = false;
- }
- switch (e.type) {
- case 'checkbox':
- case 'radio':
- if (!e.checked) { break; }
- case 'hidden':
- case 'password':
- case 'text':
- if (!isarray) {
- json += '"' + name + '":';
- }
- json += '"' + e.value.replace(new RegExp('(["\\\\])', 'g'), '\\$1') + '",';
- break;
- case 'button':
- case 'file':
- case 'image':
- case 'reset':
- case 'submit':
- default:
- }
- };
- return json.substring(0, json.length - 1) + '}';
- }
使用很简单:
- json_string = formToJSON(document.forms["myform"]);
- // 用 mootools 的 ajax 提交
- new Ajax('test.php', {
- postBody: 'json=' + encodeURIComponent(json_string),
- onComplete: afterDataFormSubmit
- }).request();
test.php 收到后:
- <?php
- $json = $_POST['json'];
- // 使用 PHP 5.2 的 json_decode() 解析
- $arr = json_decode($json, true);
- print_r($arr);
- // 使用 PEAR::Services_JSON 解析
- $services = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
- $arr = $services->decode($json);
- print_r($arr);
这里解析都是强制解析为 php 的数组。一是这样方便使用,二是嵌套的数据可以解析出来。
相关阅读 更多 +