简单的jQuery,PHP和JSONP的例子吗? [英] Simple jQuery, PHP and JSONP example?

查看:116
本文介绍了简单的jQuery,PHP和JSONP的例子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临着同样的原产地政策的问题,并通过研究这个问题,我发现,我的特定项目的最佳方法是使用JSONP做跨域请求。

I am facing the same-origin policy problem, and by researching the subject, I found that the best way for my particular project would be to use JSONP to do cross-origin requests.

我一直在阅读这篇文章来自IBM约JSONP ,但我不100%清楚是怎么回事。

I've been reading this article from IBM about JSONP, however I am not 100% clear on what is going on.

所有我要求在这里,是一个简单的jQuery> PHP JSONP请求(或其他术语的含义;)) - 像这样(这显然是不正确,它只是让你可以得到的想法我试图实现:))

All I am asking for here, is a simple jQuery>PHP JSONP request (or whatever the terminology may be ;) ) - something like this (obviously it is incorrect, its just so you can get an idea of what I am trying to achieve :) ):

jQuery的:

$.post('http://MySite.com/MyHandler.php',{firstname:'Jeff'},function(res){
    alert('Your name is '+res);
});

PHP:

<?php
  $fname = $_POST['firstname'];
  if($fname=='Jeff')
  {
    echo 'Jeff Hansen';
  }
?>

我将如何转换到这一个适当的JSONP请求?如果我是存储HTML在结果中返回,将这项工作吗?

How would I go about converting this into a proper JSONP request? And if I were to store HTML in the result to be returned, would that work too?

推荐答案

当你使用$ .getJSON对外部域,它会自动行动JSONP请求,例如我的<一个href="http://small$c$crs.com/2011/06/development-environment/freebies/tweet-slider-v2-2-now-a-lightweight-jquery-plugin/">tweet滑块这里

When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here

如果你看一下源$ C ​​$ C,你可以看到,我打电话使用.getJSON Twitter的API。

If you look at the source code you can see that I am calling the Twitter API using .getJSON.

所以,你的例子是: 这是测试和工程(你可以去<一href="http://small$c$crs.com/javascriptdevenvironment.html">http://small$c$crs.com/javascriptdevenvironment.html看到它在行动)

So your example would be: THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)

//JAVASCRIPT

$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
    alert('Your name is '+res.fullname);
});

//SERVER SIDE
  <?php
 $fname = $_GET['firstname'];
      if($fname=='Jeff')
      {
          //header("Content-Type: application/json");
         echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

      }
?>

注意?回调=?和+ res.fullname

Note the ?callback=? and +res.fullname

这篇关于简单的jQuery,PHP和JSONP的例子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆