2013-07-05 2 views
0

지금 jsonp을 배우고 있습니다. 현재이 테스트 요청을받을 수 없습니다.jsonp로 처음 시도한 후 스크립트가 작동하지 않습니다.

메인 스크립트가 이와 같이 보이는 파일이 있습니다. 내가 jsfiddle.net에 가서 실행하면

(function(){ 
var jQuery; 

if (window.jQuery==undefined || window.jQuery.fn.jquery!=='1.8.1'){ 
var script_tag=document.createElement('script'); 
script_tag.setAttribute("type", "text/javascript"); 
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"); 

if(script_tag.readyState){ 
script_tag.onreadystatechange=function(){ 
    if(this.readyState=='complete' || this.readyState=='loaded'){ 
    scriptLoadHandler(); 
    } 
    }; 
}else{ 
    script_tag.onload=scriptLoadHandler; 
    } 
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag); 
}else{ 
jQuery=window.jQuery; 
main(); 
} 

function scriptLoadHandler(){ 
jQuery=window.jQuery.noConflict(true); 
main(); 
} 

function main(){ 
$(document).ready(function($){ 
    var jsonp_url = "http://www.reflap.com/beta/assets/js/atest.php?callback=theresponse"; 
     $.getJSON(jsonp_url, 'name=Michael', function(data) { 
      alert (data.fullname); 
     }); 
}); 
} 
})(); 

그리고 atest.php에서 서버

내가 그러나이

<?php 
function theresponse(){ 
$fname= $_GET['name']; 

if($fname=='Michael'){ 
echo $_GET['callback']. '(' . "{'fullname':'Michael Yeah'}" . ')'; 
} 
else 
echo "Your not allowed here"; 
} 
?> 

<script src="http://www.reflap.com/beta/assets/js/widget2.js"></script> 

이 경고 상자를 시작하지 않습니다 . 뭐가 문제 야? 나는 실수 한 부분을 정말로 보지 못한다.

답변

0

$.getJSON은 JSONP가 아닌 일반 JSON 용입니다. 시도해보십시오 :

var jsonp_url = "http://www.reflap.com/beta/assets/js/atest.php'; 
$.ajax({ 
    url: jsonp_url, 
    dataType: 'jsonp', 
    data: { name: 'Michael' } 
}).done(function(data) { 
    alert(data.fullname); 
}); 

URL에 callback=?을 넣지 않아도됩니다. jQuery가 그 자체로 처리합니다.

+0

jsonpCallback이 필요하지 않습니까? ajax 호출에서 'theresponse'가 필요합니까? –

+0

할 수는 있지만 필수는 아닙니다. jQuery는 일반적으로 자체 내부 콜백 함수를 사용합니다. – Barmar

+0

그러면 서버 코드에 오류가 있습니다. 왜냐하면이 함수는 theresponse()라는 함수를 감쌌다. –

관련 문제