javascript 经典 ASP:如何使用 AX json 实现将 RecordSet 转换为 json 表示法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9332909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Classic ASP: how to convert a RecordSet to json notation using AXE json implementation
提问by Rafael
i'm doing an application with ajax using jQuery and some other tools, and in some part i want to retrieve data with ajax using a classic ASP backend, i saw that exists a good implementation of a JSON class in AXE (Asp extreme edition) framework, and i used it but currently i don't understand how to use it well.
我正在使用 jQuery 和其他一些工具使用 ajax 做一个应用程序,在某些部分我想使用经典的 ASP 后端使用 ajax 检索数据,我看到在 AX 中存在一个 JSON 类的良好实现(Asp 极限版)框架,我用过它,但目前我不明白如何很好地使用它。
Edit: based on the correct answerof JSON.Stringify fails on Scripting.Dictionary objectsThread, i decided to make a custom function to process Recordsets.
编辑:基于对正确答案的JSON.Stringify失败对对象的Scripting.Dictionary主题,我决定做一个自定义函数来处理记录集。
Edit 2:Now i'm losing the value data when call JSON.stringifyinside function JSONStringify(object).
编辑 2:现在我在函数 JSONStringify(object) 中调用JSON.stringify时丢失了值数据。
when the Recordset is passed as value to JSONStringifyeverything is ok but when JSON.stringifyis executed, the "value" parameter that must contain the recordset becomes undefined
当记录集作为值传递给JSONStringify 时一切正常,但是当JSON.stringify被执行时,必须包含记录集的“值”参数变为未定义
What i'm expecting (example)
我在期待什么(示例)
passing a Recordset with from a SQL query SELECT name, tel FROM users
a see an output like this
从 SQL 查询传递 RecordsetSELECT name, tel FROM users
看到这样的输出
[
{"name":"Jonh Smith", "tel":"12345678"},
{"name":"April Michelson", "tel":"77788802"},
...
]
passing a Dictionary and see something similar based in the elements declared in dictionary.
传递字典并查看基于字典中声明的元素的类似内容。
{
"element1":"value1",
"element2":"value2",
"element3":"value3",
"element4":"value4",
"element5":"value5"
}
and if i like to support other type object i can do it expanding the function
如果我喜欢支持其他类型的对象,我可以扩展功能
Source Code
源代码
getcatalogos.asp
获取目录
<!--#include file="../includes/conexion.asp" -->
<!--#include file="../includes/json2.asp" -->
<!--#include file="../includes/json-stringify-parser.asp" -->
<%
Response.ContentType = "application/json"
dim aVals(2)
function getCatalogo(tipo, params)
Dim oConn,oCmd,sSQL,oRs,cont2
Dim aData,oPar,cont
dim Info
set oConn = Server.CreateObject("ADODB.Connection")
set oCmd = Server.CreateObject("ADODB.Command")
sWhere = ""
oConn.ConnectionString = strcon
oConn.Open
Set oCmd.ActiveConnection = oConn
select case tipo
case "g"
sSQL = " SELECT cve_gr, descr FROM gr ORDER BY descr ;"
case "z"
sSQL = " SELECT cve_zn, descr FROM zn WHERE cve_gr = ? ORDER BY descr ;"
if IsArray(params) Then
Set oPar=oCmd.CreateParameter (params(0),129,1,2,params(1))
oCmd.Parameters.Append(oPar)
End if
case else
getCatalogo = false
exit function
end select
oCmd.CommandText = sSQL
Set oRs = oCmd.Execute()
if Not oRs.EOF Then
response.write(JSONStringify(oRs))
getCatalogo = true
else
getCatalogo = false
end if
oConn.Close
end function
aVals(0) = "cve_gr"
aVals(1) = request.querystring("gr")
if Not getCatalogo(request.querystring("t"),aVals) Then
%>error<%
end if
%>
json-stringify-parser.asp
json-stringify-parser.asp
<!--#include file="vbsTyper.asp" -->
<script runat="server" language="JScript">
function JSONStringify(object) {
VBSTypeName(object);
return JSON.stringify(object,stringifyData);
}
function stringifyData(holder, key, value) {
var sType = '';
var result;
//response.write('pre...holder=' + holder + ',key=' + key + ',value=' + value);
sType = VBSTypeName(value);
//response.write('post =' + sType);
//response.write(sType);
switch(sType){
case 'Dictionary':
result = '{';
for(var enr = new Enumerator(value); !enr.atEnd(); enr.moveNext()){
key = enr.item();
result += '"' + key + '": ' + JSON.stringify(value.Item(key));
};
result += '}';
return(result);
break;
case 'Recordset':
response.write('here!!!');
var sTemp = '';
result = '{';
while(!value.EOF){
if(Len(result) > 0){
result += ',';
}
result += '{';
for (var i = value.Fields.Count - 1; i >= 0; i--){
if(len(sTemp) > 0){
sTemp += ',';
}
sTemp += '"' + value.Fields(i).name + '":' + JSON.stringify( value.Fields(i).value);
};
result += '}';
}
result += '}';
return result;
break;
default:
//response.write(sType);
return(value);
}
// return the value to let it be processed in the usual way
return result;
}
</script>
vbsTyper.asp
vbsTyper.asp
<%
Function VBSTypeName(Obj)
dim sType
sType = Cstr(TypeName(Obj))
response.write(sType)
VBSTypeName = sType
End Function
%>
采纳答案by Rafael
kind of achieve it...
有点实现它...
Short version:i had to modify the json2.asp and hack the stringify() function definition to make it works.
简短版本:我不得不修改 json2.asp 并修改 stringify() 函数定义以使其工作。
Long Version
长版
later of see every line of code and giving up on the problem. i decided to take a look into json2.asp(AXE Framework) and try to see what it happening there.
稍后查看每一行代码并放弃问题。我决定研究一下json2.asp(AXE 框架)并尝试看看它在那里发生了什么。
look what i see:
看看我看到了什么:
from the lines 682 to 687 theres a validation if a custom stringy parser is found but later doesn't do anything ... only returns the Object value.
从第 682 行到第 687 行,如果找到自定义字符串解析器,则进行验证,但稍后不执行任何操作……仅返回 Object 值。
there's speculation from here, because i don't understand well how works every Javascript implementation, but implyingthat the original code runs well, that a standart javascript interpreter (read everything else but microsoft here) will force a serialization of the object in this sutuation, but the JScript interpreter try to parse the object and pass the value as null. resulting in that every function that uses a custom stringyfier can't read the object passed in the function.
这里有一些猜测,因为我不太了解每个 Javascript 实现是如何工作的,但暗示原始代码运行良好,标准的 javascript 解释器(在这里阅读除微软之外的所有内容)将强制在这种情况下对对象进行序列化,但 JScript 解释器尝试解析对象并将值作为null传递。导致每个使用自定义 stringyfier 的函数都无法读取函数中传递的对象。
what i did to resolve ok i inserted this chunk of code before line 688, forcing to execute the custom stringyfier with value directly passed as argument avoiding the implicit parsing.
我做了什么来解决 ok 我在第 688 行之前插入了这段代码,强制执行自定义 stringyfier,其值直接作为参数传递,避免了隐式解析。
// Hack & patch to deliver the stringify-ing of the object correctly
// IDK if this is CORRECT or dont but it works in VbScript
if(replacer){
var textval = rep(this,'',value);
value = textval;
}
later i had to do some changes in json-stringify-parser.aspbecause i had to fix some bugs resulting in this code
后来我不得不在json-stringify-parser.asp 中做一些更改,因为我必须修复导致此代码的一些错误
<!--#include file="vbsTyper.asp" -->
<script runat="server" language="JScript">
function JSONStringify(object) {
//VBSTypeName(object);
return JSON.stringify(object,stringifyData,4);
}
function stringifyData(holder, key, value) {
var sType = '';
var result;
//response.write('pre...holder=' + holder + ',key=' + key + ',value=' + value);
sType = VBSTypeName(value);
//response.write('post =' + sType);
//response.write(sType);
switch(sType){
case 'Dictionary':
result = '{';
for(var enr = new Enumerator(value); !enr.atEnd(); enr.moveNext()){
key = enr.item();
result += '"' + key + '": ' + JSON.stringify(value.Item(key));
};
result += '}';
return(result);
break;
case 'Recordset':
//response.write('here!!!');
var sTemp;
result = '';
while(!value.EOF){
if(result.length > 0){
result += ',';
}
result += '{';
sTemp=''
for (var i = 0; i < value.fields.Count; i++){
if(sTemp.length > 0){
sTemp += ',';
}
//response.write("i=" + i + ",");
sTemp += '"' + value.fields.item(i).name + '":' + JSON.stringify( value.fields.item(i).value);
};
result += sTemp + '}';
value.moveNext();
}
result = '{' + result + '}';
return result;
break;
default:
//response.write(sType);
return(value);
}
// return the value to let it be processed in the usual way
return result;
}
</script>
the part to parse a Recordset works, the part to parse a dictionary is same like the shown in JSON.Stringify fails on Scripting.Dictionary objects(a.k.a. i haven't tested yet) but for now i'm done with this.
解析 Recordset 的部分有效,解析字典的部分与JSON.Stringify 中显示的相同,Scripting.Dictionary 对象(也就是我还没有测试过)失败,但现在我已经完成了。
testing my changes with a recordset object results in this output
使用记录集对象测试我的更改会导致此输出
"{
{\"clave\":\"BC\",\"descripcion\":\"Cal\"},
{\"clave\":\"CT\",\"descripcion\":\"Center\"},
{\"clave\":\"NE\",\"descripcion\":\"Norw\"},
{\"clave\":\"NO\",\"descripcion\":\"Nore\"},
{\"clave\":\"NT\",\"descripcion\":\"North\"},
{\"clave\":\"OC\",\"descripcion\":\"East\"},
{\"clave\":\"OR\",\"descripcion\":\"West\"},
{\"clave\":\"PE\",\"descripcion\":\"Pen\"},
{\"clave\":\"SE\",\"descripcion\":\"Southe\"},
{\"clave\":\"ZM\",\"descripcion\":\"Met\"}
}"
Questions Left
剩下的问题
question that i have left withis kind of hack.
我留下的问题有点像黑客。
it's Ok that the output has (") character at the beggining and the end and i everything else has escape sencuences ?? or it's something that should not occurs.
this kind of hack is really wrong ... i can do it better, in this kind of situation ?
it's something wrong in my conclusion or arguments ??
输出在开始和结束时具有 (") 字符是可以的,我其他所有内容都有转义 ?? 或者这是不应该发生的事情。
这种黑客真的是错误的......我可以做得更好,在这种情况下?
我的结论或论点有问题吗??
回答by Nathan Rice
This:
这:
response.write(JSON.stringify(oRs))
Should read something like this:
应该是这样的:
Do Until oRS.EOF
response.write(JSON.stringify(oRs("cve_gr") & ":" & oRs("descr"))
oRS.MoveNext
Loop