简单的 jQuery、PHP 和 JSONP 示例? [英] Simple jQuery, PHP and JSONP example?
问题描述
我正面临同源策略问题,通过研究该主题,我发现我的特定项目的最佳方法是使用 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 请求,例如我的 推特滑块在这里
When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here
如果您查看源代码,您会发现我正在使用 .getJSON 调用 Twitter API.
If you look at the source code you can see that I am calling the Twitter API using .getJSON.
所以你的例子是:这已经过测试并且有效(您可以转到 http://smallcoders.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'}" . ')';
}
?>
注意 ?callback=?和 +res.fullname
Note the ?callback=? and +res.fullname
这篇关于简单的 jQuery、PHP 和 JSONP 示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!