2014-10-01 2 views
0

저는 JSON 및 웹 개발 자료에 익숙하지 않습니다. 그래서 문제를 적절하게 제시 할 수 없다면 용서해주십시오.JSON : 응답을 받았지만 jQuery에서 표시 할 수 없습니다.

사이트에서 JSON 응답을 받았지만 콘솔에 프롬프트 된 오류와 함께 응답 데이터를 표시 할 수없는 상황이 있습니다.

나는 파이어 폭스와 크롬을 시험해 보았습니다. 둘 다 다른 오류를 주었다.

파이어 폭스 = "구문 에러 : 실종, 문 앞에

크롬 ="catch되지 않은 구문 에러 :.. 예기치 않은 토큰 "나는 이미 jQuery를 API를 통해 호출하는 두 가지 유형을 시도

아래는 내 샘플 코드입니다

<html> 
<body> 
    <button>Click Me!</button> 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
    <script> 
     $("button").click(function() 
     { 
      $.getJSON("http://rate-exchange.herokuapp.com/fetchRate?from=SGD&to=MYR&lang=en-us&format=json&jsoncallback=?", function(data) { 
        console.log(data); 
        var info = JSON.parse(data); 
        alert(rate); 
       });  
     }) 
    </script> 
</body></html> 



    <html> 
<body> 
    <button>Click Me!</button> 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
    <script> 
     $("button").click(function loadRate() 
     { 
      $.ajax({ 
       type:'GET', 
       url:"http://rate-exchange.herokuapp.com/fetchRate", 
       data:"from=SGD&to=MYR"+"&lang=en-us&format=json&jsoncallback=?", 
       dataType:'json', 
       success:function(resp){ 
        var parse = JSON.parse(resp); 
        alert(parse.Rate); 
       } 
      }); 
     }) 
    </script> 
</body></html> 

그리고 JSON API의 난을 참조는 다음 http://rate-exchange.herokuapp.com/

응답 D ATA는 다음과 같이이다 : { "받는 사람" "에서" "MYR", "SGD", "속도" "2.5666"}

답변

2

1)이 라인

2) alert(rate);에서 var info = JSON.parse(data); 필요가 없습니다 것 rate입니까? 여기

3) .click(function loadRate() 기능은 .click(function()

4) var parse = JSON.parse(resp); 필요가 없습니다, JQuery와 자동 dataType:'json'

+0

3) 왜 : 여기

가 작동하는 예입니다? 명명 된 함수 표현식에는 아무런 문제가 없습니다. 나열된 모든 것들이 정확할 수도 있지만, JSONP가 예상 될 때 JSON을로드하는 실제 문제를 다루는 것은 없습니다. –

+0

@FelixKling API를 살펴보면 JSON이 아니라 JSONP를 반환합니다. 'jsoncallback'과 관련된 부분은 다른 곳에서 왔습니다. – Cheery

+0

JSON을 반환한다는 것을 알고 있습니다. 이것이 OP가받는 오류 메시지의 이유입니다. jQuery는 JSON이 아니라 JSONP를 기대한다. –

1

은 적어도 첫 번째 경우에, 당신이 말할 때 JSON을 구문 분석, 어떤 이름이 안 indirectly tell jQuery to expect JSONP :

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

JSONP은 아무것도하지만, 동적으로 <script> 요소를 추가하고 일부 자바 스크립트를 평가하지 않습니다 (실제로 JSON과 아무 관련이 없습니다). 그러나 서버는 일반 JSON이 아닌 JavaScript 함수 호출을 반환해야하므로 서버에서 지원해야합니다.

응답에서 볼 수 있듯이 JSON이며 함수 호출이 아닙니다. 당신이 jsoncallback=? 부분 you get a different error을 제거하면

> {"To":"MYR","From":"SGD","Rate":"2.5666"} 
SyntaxError: Unexpected token : 

: 콘솔에 직접 넣을 경우 동일 (또는 유사) 오류를 얻을 것이다 (JS로 평가하기)

XMLHttpRequest cannot load http://rate-exchange.herokuapp.com/fetchRate?from=SGD&to=MYR&lang=en-us&format=json . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access.

API는 JSONP 또는 CORS를 지원하지 않는 것 같습니다. 따라서 Ajax 요청을 직접 서비스에 적용 할 수는 없습니다. 예를 들어 액세스 권한에 액세스하는 다른 방법을 찾아야합니다. 자신 또는 공용 프록시 (예 : https://github.com/Rob--W/cors-anywhere)를 통해

은 참조 : Ways to circumvent the same-origin policy

+0

물론 CORS를 사용하도록이 서비스 개발자에게 요청할 수도 있습니다. –

0

하나를 들어, JSONP 콜백을 사용하는 방법에 대한 @Felix 클링의 반응은 사실이다, 그래서를 제거합니다.

둘째, 매우 오래된 jQuery 버전을 사용하고 있으므로 1.11.1로 업그레이드하시기 바랍니다.

<html> 
    <body> 
     <button>Click Me!</button> 

     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
     <script> 
      $(function() { 
       $("button").click(function() { 
        var url = "http://rate-exchange.herokuapp.com/fetchRate?from=SGD&to=MYR&lang=en-us&format=json"; 
        $.getJSON(url) 
         .done(function (result) { 
          console.log('Success: ', result); 
         }) 
         .fail(function() { 
          console.log('Fail'); 
         }); 
       }); 
      }); 
     </script> 
    </body> 
</html> 
+0

또한 필자의 대답에서이 API는 CORS를 사용할 수 없기 때문에 Ajax 요청을 할 수 없다. 참조 : http://jsfiddle.net/vnmmurqc/ –

+0

당신 말이 맞아요. JavaScript에서 크로스 도메인 보안의 영향을받지 않는 로컬 파일에서 테스트 중이므로 처음에는 CORS 문제가 표시되지 않았습니다. –

관련 문제