【发布时间】:2015-01-14 13:38:49
【问题描述】:
总结
我有一个运行搜索的应用程序。在允许提交之前,它会向查询发送 AJAX 调用以检查有效的邮政编码,然后返回我可以解析的 JSON 结果。我现在需要跨域做同样的事情,我知道我必须使用完整的 url 和 JSONP 格式,但我不确定如何设置它。
AJAX 调用
我发送了一个通过查询运行的邮政编码。
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>
JSON 响应
这是查询返回的内容。
{"message":"Invalid Zip","formError":true}
处理响应
正如我在上面的 AJAX 成功函数中所做的那样,我可以从 JSON 响应中获取 formError 或 message 变量。如何使用 JSONP 做到这一点?
success: function(obj) {
var response = $.parseJSON(obj);
if (response.formError == true) {
alert(response.message);
}
}
【问题讨论】:
标签: jquery ajax json coldfusion jsonp