[英]jsonp, jQuery & PHP to make cross-domain ajax call
html: HTML:
<form id="myform">
<input id="inputfield" name="view">
</form>
js: JS:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: inputdata,
dataType: 'jsonp'
});
});
php: PHP:
<?php
$view = $_GET['callback'].'('.json_encode(name) .')';
?>
html: HTML:
<h4><?php echo $view; ?></h4>
what the code does is: 代码的作用是:
from serverA, assign a value "ocean-view" to an input field, submit this form to serverB, and display this value in a h4 tag. 在serverA中,为输入字段分配一个“ ocean-view”值,将该表单提交给serverB,并在h4标签中显示该值。
I couldn't quite figure out how to write the server-side code to output the value, even though I have found the following posts. 即使我发现了以下帖子,我也不太清楚如何编写服务器端代码来输出值。
Any kind of help is appreciated. 任何帮助都将受到赞赏。
UPDATE: I used YQL to help to see the jsonp callback response, here is the json structure: 更新:我使用YQL来帮助查看jsonp回调响应,这是json结构:
callback({
"query": {
"count": 1,
"created": "2013-07-29T13:01:12Z",
"lang": "en-US",
"results": {
"h3": {
"class": "mytitle",
"content": "Example"
}
}
}
});
Actually You are very close to success... just read these points. 实际上,您非常接近成功……请阅读这些要点。
Formats are: 格式为:
text/html
json
xml
......
Mainly for cross domain requests we use JSONP. 主要针对跨域请求,我们使用JSONP。 And it means PHP script will return data in JSON.
这意味着PHP脚本将以JSON返回数据。 So you will just echo your
json_encode
in directly script. 因此,您将直接在脚本中回显
json_encode
。 That will be the response of your ajax request. 那将是您的ajax请求的响应。
These thing can be analyzed in any browser in debug console. 这些东西可以在调试控制台的任何浏览器中进行分析。 That what is requested and what is returned.
那是什么要求,什么返回。 even you can use Firebug in Mozilla to inspect ajax request.
即使您可以在Mozilla中使用Firebug来检查ajax请求。
So you will do three changes. 因此,您将进行三个更改。
In Ajax function write a success function: 在Ajax函数中编写一个成功函数:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: "inputdata="+inputdata,
dataType: 'jsonp',
success:function(response){
// response will be json type so access it
// print ur json in html tag like resposne is {"data":23}
$(<jquery selector>).html(reponse.data);
}
});
}); });
<?php
// echo this
$inputdata = $_GET['inputdata'];
// perform you logic ,
// make an array to encode it in json
echo $_GET['callback'].'('.json_encode($responseArr) .')';
?>
and remove PHP code from h4 tag. 并从h4标记中删除PHP代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.