1
$.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);                  
}
});

cf函数是;

<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 中访问这些数据?

4

3 回答 3

2
success: function(response, textStatus, jqXHR) {
    console.log(response.phone);
    console.log(response.state);
}
于 2013-07-09T10:38:21.457 回答
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/

于 2013-07-13T03:24:16.317 回答
0

将您的重新格式化更改为普通格式 像这样

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

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

于 2013-07-10T09:54:33.723 回答