Jquery Ajax使用coldfusion 9进行调用:JSON.parse:意外字符

时间:2011-11-11 08:25:45

标签: jquery ajax coldfusion

我是AJAX的新手所以我为此道歉。

我正在尝试使用<cfquery>从cfc组件中的数据库中提取数据,然后使用serializeJSON(var)函数将其转换为JSON。但在萤火虫中我最终出现了“意外角色”错误。查询中确实有文件路径,因此可能与问题有关,或者我对AJAX调用的所有错误都是错误的?

<cfcomponent>
<cffunction name="getStuff" access="remote" returnFormat="json">
    <cfargument name="userID" type="numeric" required="yes">
    <cfset datasrc = “data">
    <cfset pass = "">
    <cfquery datasource="#datasrc#" password="#pass#" name="getData" maxrows="25">
            SELECT blah
                FROM blah
                WHERE blah = ‘#userID#'
    </cfquery>
    <cfset jsondata = serializeJSON(getData)>
    <cfdump var="jasondata">
    <cfreturn jsondata>
</cffunction>

使用Javascript:

function populateBrews(id) {    
$.ajax({

    url: "/components/Object.cfc"

  , type: "get"

  , dataType: "json"

  , data: {
  method: "getStuff"

 , userId: id
 }

 , success: function (data){
 }

, error: function (xhr, textStatus, errorThrown){ 
alert(errorThrown);
}
});
}

5 个答案:

答案 0 :(得分:4)

你是JSON-ifying你的JSON。看看你如何在函数中使用returnFormat = json?这告诉CF取结果并将其转换为JSON。但是,当您返回结果时,您将自己创建一个JSON字符串。基本上,您正在序列化已经序列化的结果。变化

<cfset jsondata = serializeJSON(getData)>
<cfdump var="jasondata">
<cfreturn jsondata>

<cfreturn getData>

答案 1 :(得分:1)

确保关闭了请求调试 - 调试输出将破坏json解析。

答案 2 :(得分:0)

试试这个:使用json2.js

var postdata = new Object(); 
postdata.parameter1 = <value>; 
postdata.parameter2 = <value>;  

$.ajax({  
type: "POST",  
url: "url",  
dataType: "application/json",  //this is important
data: JSON.stringify(postdata),  
async: true,  
success: function (data) { Handler_Success(data); }  
});  
});  

答案 3 :(得分:0)

我确信雷的回答是正确的。你的函数应该保持returnformat = json并且只返回getData结果集而不做任何修改。

如果您是在Windows上进行开发,我建议您使用Fiddler并使用它来查看来自浏览器的请求以及来自CF的响应。使用RAW和JSON Response检查器可以准确查看CF返回的内容。我们经常不得不将下面的代码添加到我们的删除CFC方法中,以确保不包含其他会破坏JSON的输出:

答案 4 :(得分:0)

正如许多答案所提到的,请检查您的XHR.responseHeader ...您的数据很可能会返回类似<WDDX packet version='1.0'><header/><data>...的内容,然后是您的JSON格式的响应。

如果是这种情况,请添加responsetype='JSON'以删除WDDX格式。