[英]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. 因此,我现在正在学习jsonp,并且目前无法使该测试请求正常工作。
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 在服务器上atest.php我有这个
<?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 但是当我进入jsfiddle.net并执行时
<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. $.getJSON
用于普通JSON,而不是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=?
您不需要放置callback=?
in the URL, jQuery will do that itself. 在URL中,jQuery会自行执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.