[英]Script not working after first attempt with jsonp
因此,我現在正在學習jsonp,並且目前無法使該測試請求正常工作。
我有一個文件,其中主腳本出現如下所示。
(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";
}
?>
但是當我進入jsfiddle.net並執行時
<script src="http://www.reflap.com/beta/assets/js/widget2.js"></script>
它不會啟動警報框。 怎么了? 我真的看不出我在哪里犯了錯誤。
$.getJSON
用於普通JSON,而不是JSONP。 嘗試:
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);
});
您不需要放置callback=?
在URL中,jQuery會自行執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.