dqly83915
2011-12-15 05:47
浏览 39

你如何使用PHP和jquery获取jsonp?

I have this PHP:

$response = 'success';
$response = json_encode($response);
echo $_GET['callback'] . '('.$response.')';

and this jQuery:

$.ajax({url: "/*url*/?invite="+getinvite+"&api="+api, dataType:"jsonp", 
    success: function(response){/*do stuff*/}});

On XAMPP on my laptop it was working great. Then when I put it on my server it gives me this error: Undefined index: callback.

Why is it not letting me set $_GET['callback']? and how would this problem be fixed?

图片转代码服务由CSDN问答提供 功能建议

我有这个PHP:

  $ response ='success  '; 
 $ response = json_encode($ response); 
echo $ _GET ['callback']。  '('。$ response。')'; 
   
 
 

这个jQuery:

  $ .ajax(  {url:“/ * url * /?invite =”+ getinvite +“& api =”+ api,dataType:“jsonp”,
成功:函数(响应){/ *做东西* /}}); \  n   
 
 

在我的笔记本电脑上的XAMPP上工作得很好。 然后,当我把它放在我的服务器上时,它给了我这个错误: Undefined index:callback

为什么不让我设置 $ _ GET [ '回调'] ? 以及如何解决这个问题?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dpdbu24262 2011-12-15 06:08
    已采纳

    You aren't setting a parameter called 'callback' and so it isn't set in the $_GET variables.

    You could fix the error message by doing:

    $callback = "";
    if(array_key_exists('callback', $_GET) == TRUE){
        $callback = $_GET['callback'];
    }
    

    However I don't think you may have misunderstood the .ajax call in jQuery - the javascript function that is called on success is not passed to the server; it is only held inside jQuery.

    打赏 评论
  • dpvp56187 2011-12-15 06:14

    To make your ajax call simple, use getJson method designed specifically for JSONP response.

    http://api.jquery.com/jQuery.getJSON/

    This will automatically create a callback function name which will be passed as parameter to your jsonp api . example from the page :

    $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
      {
        tags: "cat",
        tagmode: "any",
        format: "json"
      },
      function(data) {
        $.each(data.items, function(i,item){
          $("<img/>").attr("src", item.media.m).appendTo("#images");
          if ( i == 3 ) return false;
        });
      });
    
    打赏 评论

相关推荐 更多相似问题