Coldfusion Jquery Ajax数据格式

时间:2013-07-09 10:34:10

标签: jquery ajax coldfusion

$.ajax({
type: 'Get',
url: '/services/user.cfc?method=GetCompanyJson',
data: 'Companyid=' + ui.item.id,
datatype: 'json',
error: function(xhr, textStatus, errorThrown) {
// show error
alert(errorThrown)},
success: function(response, textStatus, jqXHR) {
alert(response);
$('#Company_Name').val(response.name);                  
}
});

cffunction是;

<cffunction name="GetCompanyJson" access="remote" returntype="struct"     returnformat="json" output="false">
        <cfargument name="Companyid" required="true" />
        <cfquery name="QComp" datasource="#request.dsn_live#">
        select id,name,address_line_1,address_line_2,city,state,zip,phone
        from companies
        where id = #val(arguments.Companyid)#
    </cfquery>
    <cfset var comp = structNew() />
    <cfset comp["ID"] = '#qcomp.ID#' />
    <cfset comp["name"] = '#qcomp.name#' />
    <cfset comp["address_line_1"] = '#Qcomp.address_line_1#' />
    <cfset comp["address_line_2"] = '#Qcomp.address_line_2#'/>
    <cfset comp["city"] = '#Qcomp.city#' />
    <cfset comp["state"] = '#Qcomp.state#' />
    <cfset comp["zip"] = '#Qcomp.zip#' />
    <cfset comp["phone"] = '#Qcomp.phone#' />
        <cfreturn comp>
    </cffunction>

返回的数据是;

"{"phone":"8634500","state":"CA","zip":"92618","name":"Taco Bell Corp","ID":"2200","city":"Irvine","address_line_2":"","address_line_1":"1 Glen Bell Way"}"

如何在Javascript中访问此数据?

3 个答案:

答案 0 :(得分:2)

success: function(response, textStatus, jqXHR) {
    console.log(response.phone);
    console.log(response.state);
}

答案 1 :(得分:0)

将您重新格式化为简单 喜欢这个

<cffunction name="GetCompanyJson" access="remote" returntype="struct"     returnformat="plain">

现在您可以将其访问到Ajax成功请求中。

答案 2 :(得分:0)

尝试在响应对象上使用jQuery.parseJSON(),如下所示:

success: function(response, textStatus, jqXHR) {
    var RespObj = jQuery.parseJSON(response);
    console.log(RespObj.phone);
    console.log(RespObj.state);
}

我认为这应该有效。您还可以使用.getJSON()替换.ajax()调用,并返回已解析的对象。

http://api.jquery.com/jQuery.parseJSON/

http://api.jquery.com/jQuery.getJSON/