JSONP get JSON data through AJAX Cross-domain requests

Source: Internet
Author: User
Tags php code php json

Related articles: PHP JSON data creation and resolution program code


JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration script tags to be returned to the client and Cross-domain access through JavaScript callback (this is simply a JSONP form of implementation).

Client-side HTML code:

The code is as follows Copy Code

<meta content= "text/html; Charset=utf-8 "http-equiv=" Content-type "/>
<script type= "Text/javascript" >
function Jsonpcallback (Result) {
alert (result);
for (var i on result) {
Alert (i+ ":" +result[i]);//loop output a:1,b:2,etc.
}
}
var jsonp=document.createelement ("script");
Jsonp.type= "Text/javascript";
Jsonp.src= "Http://crossdomain.com/services.php?callback=jsonpCallback";
document.getElementsByTagName ("Head") [0].appendchild (JSONP);
</script>



Service-Side PHP code

The code is as follows Copy Code


<?php

Server side returns JSON data
$arr =array (' A ' =>1, ' B ' =>2, ' C ' =>3, ' d ' =>4, ' e ' =>5);
$result =json_encode ($arr);
Echo $_get[' callback ']. ' ("hello,world!") ';
Echo $_get[' callback ']. " ($result) ";
Dynamic execution of callback functions
$callback =$_get[' callback '];
echo $callback. " ($result) ";

?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.