【问题标题】:Script not working after first attempt with jsonp第一次尝试使用 jsonp 后脚本无法正常工作
【发布时间】:2013-07-03 04:26:52
【问题描述】:

所以我现在正在学习 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);
        });
});
}
})();

在 attest.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>

它不会启动警报框。怎么了?我真的不明白我在哪里犯了错误。

【问题讨论】:

    标签: php javascript json jsonp


    【解决方案1】:

    $.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 会自己做。

    【讨论】:

    • 在 ajax 调用中我不需要 jsonpCallback: 'theresponse' 吗?
    • 您可以这样做,但这不是必需的。 jQuery 通常会使用自己的内部回调函数。
    • 那么我的服务器代码中有一个错误,因为我将它包裹在一个名为 theresponse() 的函数中
    • 我认为您的服务器代码是正确的。 jQuery 将发送callback 参数,它会在您指定jsonp 时自动发送。
    • 嗯好的。很奇怪,因为我做了所有这些更改,但我仍然无法让它工作。
    猜你喜欢
    • 2022-12-26
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多