JQuery AJAX 如何获取和解析 JSONP 而不是 JSON?

JQuery AJAX How do I get and parse JSONP instead of JSON?

摘要
我有一个 运行 搜索的应用程序。在允许提交之前,它会向查询发送一个 AJAX 调用以检查有效的邮政编码,然后 returns 我可以解析的 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 响应
这就是查询 returns.

{"message":"Invalid Zip","formError":true} 


处理响应
正如我在上面的 AJAX 成功函数中所做的那样,我可以从 JSON 响应中获取 formError 或消息变量。我如何使用 JSONP?

执行此操作
success: function(obj) {
    var response = $.parseJSON(obj);

    if (response.formError == true) {
        alert(response.message);
    }
}



对于 jsonp,您只需按照下面的示例设置数据类型

阅读:Working with JSONP

$.ajax({
    url: "http://query.yahooapis.com/v1/public/yql",

    // The name of the callback parameter, as specified by the YQL service
    jsonp: "callback",

    // Tell jQuery we're expecting JSONP
    dataType: "jsonp",

    // Tell YQL what we want and that we want JSON
    data: {
        q: "select title,abstract,url from search.news where query=\"cat\"",
        format: "json"
    },

    // Work with the response
    success: function( response ) {
        console.log( response ); // server response
    }
});

我有答案。

请注意原始发布的代码在正常的 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', zip:zip},
    //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"});