简体   繁体   中英

Script not working after first attempt with jsonp

So I'm learning jsonp right now and I can't currently get this test request to work.

I have a file that where the main script occurs looking like this.

(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);
        });
});
}
})();

And on the server at atest.php I have this

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

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

However when I go on jsfiddle.net and execute

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

It doesn't start the alert box. What's wrong? I don't really see where I made a mistake.

$.getJSON is for ordinary JSON, not JSONP. Try:

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

You don't need to put the callback=? in the URL, jQuery will do that itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM