Introduction to JQuery's $.getjson cross-domain ajax approach

Source: Internet
Author: User
Tags json php code

Client:

Using $.getjson () when transferring the first parameter, that is, the URL, if a cross-domain request must have a parameter with a value of "?", such as:

The code is as follows Copy Code
$.getjson (
"Http://202.196.35.41/json.php?callback=?",
function (data) {
alert (data);
}
};

jquery will send this "?" when it sends a request. Replace with a unique string, as shown below

and declare a variable with the same name as this string, and assign the passed-in callback function to the variable.

Service side:

The server must be a dynamic program, can not be static text files, because the server to receive the passed function name, is the above figure callback value jquery172031288272701203823_1344179936251.

The server then constructs a function-calling string that takes the value that needs to be sent to the client as a parameter.

That is: jquery172031288272701203823_1344179936251 ([here Pass parameter JSON data]).

On the PHP code.

The code is as follows Copy Code
<?php
Header (' Content-type:text/javascript; Charset=utf-8 ');
Class user{
public $id;
Public $name;
Public function __construct ($id, $name) {
$this->id = $id;
$this->name = $name;
}
}
$users = Array (new user (1, ' admin '), new User (2, ' root '));

Echo $_request[' callback ']. ' ('. Json_encode ($users). ') ';

Ajax-derived data:

jquery172031288272701203823_1344179936251 ([{"id": 1, "name": "admin"},{"id": 2, "name": "Root"}]) the client gets this data and executes the statement. The Passed-in function is called and the data is passed in, because the same function name has been specified in the return function passed in by $.getjson ().

The specific Cross-domain request is to take advantage of the nature of the JS file in the page that can introduce other domains, create a script node in the page, and point his src attribute to the dynamic file of the other domain. The browser loads the file and executes the script in it.

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.