2015-01-14 2 views
4

Резюме
У меня есть приложение, которое выполняет поиск. Прежде чем разрешить отправку, он отправляет запрос AJAX на запрос для проверки действительного почтового индекса, а затем возвращает результат JSON, который я могу проанализировать. Мне нужно сделать то же самое в кросс-домене, и я знаю, что вместо этого я должен использовать полный URL-адрес и формат JSONP, но я не уверен, как это установить.

на основе AJAX вызов
Я посылаю почтовый индекс, который получает пробежать запрос.JQuery AJAX Как мне получить JSONP вместо JSON?

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, который запускает запрос

<!---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> 


The JSON Response
Это то, что запрос возвращает.

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


Работа с откликом
Как я выше в функции успеха AJAX, я могу захватить formError или переменные сообщения из ответа JSON. Как я могу это сделать с JSONP?

success: function(obj) { 
    var response = $.parseJSON(obj); 

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



ответ

3

У меня есть ответ.

Обратите внимание, что оригинал опубликованного кода отлично работает с нормальным откликом 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, который запускает запрос

<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> 


Отформатированная JSON P Ответ

//Using the name from the jsonpCallback setting in the AJAX call 
callback({"formError": "true", "message": "Invalid Zip"}); 
+2

Пожалуйста, не создавайте вручную json, не создавайте объект и не используйте serializeJSON. Это позволит избежать возможных ошибок формата JSON из-за содержимого строк, которые вы размещаете в json. –

+0

Кроме того, несколько советов. A) Функция не должна напрямую обращаться к области «url». Вместо этого явным образом определяю «zip» и «callback» как cfarguments. b) Всегда используйте cfqueryparam для защиты от SQL-инъекции. c) Не забывайте локальную область * все * вашей локальной функции и d) нет необходимости в cfoutput в конце. Просто верните строку. Так как вы cfml везде, можете использовать 'cfreturn' вместо перехода на cfscript. – Leigh

+0

Кевин - Не уверен, могу ли я это сделать. Поскольку это уже не JSON, а JSONP и больше строки, я не уверен, что serializeJSON будет работать. – madvora

0

Для JSONP вам просто нужно установить тип данных, как в приведенном ниже примере

Read: 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 
    } 
}); 
Смежные вопросы