if (zipLength == 5) {
$.ajax({
type:"GET",//location of the cfc
url: "cfc/test.cfc",//function name and url variables to send
data: {method:'zip_lookup',zip:zip},//function run on success takes the returned json object and reads values.
success: function(obj) {
var response = $.parseJSON(obj);
if (response.formError == true) {
alert(response.message);
}
}
});
}
运行查询的Coldfusion中的CFC
<!---Makes sure entered zip exists--->
<cffunction name="zip_lookup" access="remote">
<cfquery name="qZip">
Select distinct ZipCode
From zipcodes
Where ZipCode = '#url.zip#'
</cfquery>
<!---Return an error if zip was not found--->
<cfif qZip.RecordCount EQ 0>
<cfset formError = true>
<cfset message = "Invalid Zip">
<cfelse>
<cfset formError = false>
<cfset message = "">
</cfif>
<cfoutput>
<cfset obj =
{
"formError" = formError,"message" = message
}
/>
</cfoutput>
<cfprocessingdirective suppresswhitespace="Yes">
<cfoutput>
#serializeJSON(obj)#
</cfoutput>
</cfprocessingdirective>
<cfsetting enablecfoutputonly="No" showdebugoutput="No">
</cffunction>
success: function(obj) {
var response = $.parseJSON(obj);
if (response.formError == true) {
alert(response.message);
}
}
解决方法
我有答案.
请注意,原始发布的代码与正常的JSON响应完美配合.
这是我获得JSONP响应的方式.
AJAX电话
$.ajax({
type:"GET",//Location of the cfc
url: "http://yourFullUrl/test.cfc",//Function name and url variables to send
data: {method:'zip_lookup',//Set to JSONP here
dataType:"jsonp",//The name of the function that's sent back
//Optional because JQuery will create random name if you leave this out
jsonpCallback:"callback",//This defaults to true if you are truly working cross-domain
//But you can change this for force JSONP if testing on same server
crossDomain:true,//Function run on success takes the returned jsonp object and reads values.
success: function(responseData) {
//Pulls the variables out of the response
alert(responseData.formError);
alert(responseData.message);
}
});
运行查询的Coldfusion中的CFC
<cffunction name="zip_lookup" access="remote" returntype="string" returnformat="plain" output="false">
<cfquery name="qZip">
Select distinct ZipCode
From zipcodes
Where ZipCode = '#url.zip#'
</cfquery>
<!---Return an error if zip was not found--->
<cfif qZip.RecordCount EQ 0>
<cfset formError = true>
<cfset message = "Invalid Zip">
<cfelse>
<cfset formError = false>
<cfset message = "">
</cfif>
<cfoutput>
<cfscript>
<!---Important to have double quotes around the name and value. --->
<!---I missed this before --->
return '#arguments.callback#({"formError": "#formError#","message": "#message#"});';
</cfscript>
</cfoutput>
</cffunction>
格式化的JSONP响应
//Using the name from the jsonpCallback setting in the AJAX call
callback({"formError": "true","message": "Invalid Zip"});