【问题标题】:JQuery AJAX How do I get and parse JSONP instead of JSON?JQuery AJAX 如何获取和解析 JSONP 而不是 JSON?
【发布时间】: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


    【解决方案1】:

    我有答案。

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

    【讨论】:

    • 请不要手动创建json,而是创建一个对象并使用serializeJSON。这样做可以避免由于您放置在 json 中的字符串的内容而导致的可能的 JSON 格式错误。
    • 另外,一些提示 a) 函数不应直接访问url 范围。相反,将“zip”和“callback”明确定义为 cfarguments。 b) 始终使用 cfqueryparam 来防止 sql 注入 c) 不要忘记将函数局部变量的本地范围 all 和 d) 最后不需要 cfoutput。只需“返回”字符串。既然你在其他地方都是cfml,不如使用cfreturn而不是切换到cfscript。
    • Kevin - 不知道我能不能做到。由于这实际上不再是 JSON,而是 JSONP 和更多的字符串,我不确定 serializeJSON 是否有效。
    • 函数应该是独立的。直接访问 URL 范围会降低函数的灵活性。例如,如果您将 ajax 调用切换为使用 method=POST,则该函数将中断。无论函数需要什么值,都应该明确定义为 cfarguments。然后它仍然可以工作,无论输入值存储在哪里。
    • @madvora - 我认为 Kevin 的观点是 - 使用 serializeJSON 在回调包装器内部 构造 JSON 字符串,而不是手动进行。
    【解决方案2】:

    对于 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
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多