TOC

This article is currently in the process of being translated into Vietnamese (~20% done).

AJAX:

Requesting a file from a different domain using JSONP

Ở trong chương trước, chúng ta đã nói về Same Origin Policy, không cho phép chúng ta tạo AJAX request tới domain hay subdomain khác. JSONP là giải pháp khắc phục và trong bài này chúng ta sẽ xem xét.

Trong ví dụ sau, chúng ta sẽ gọi tới một script PHP phía server nhưng ở subdomain khác. Nó trả về một mảng của hai người dùng dạng JSOn và đầu ra tương thích JSONP. Mã PHP có dạng sau:

<?php
$users = array
(
	array("name" => "John Doe", "age" => 42),
	array("name" => "Jane Doe", "age" => 39)
);
echo $_REQUEST['callback'] . "(" . json_encode($users) . ")";
?>

To see what data returned looks like, try opening the following URL in your browser:

http://tests.jquery-tutorial.net/json.php?callback=test

The result will look like this:

test([{"name":"John Doe","age":42},{"name":"Jane Doe","age":39}])

If you set the callback parameter to something else, you will see that change reflected in the output. This special notation is what separates regular JSON and JSONP. Now when JSON data is returned to jQuery, it parses it into objects that you may then access and use like any other JavaScript object. For instance, the above output would result in two objects, each with a name and an age property.

Now let's try requesting the page from jQuery and use the returned data. When you test this example, notice that we call the page on a different subdomain (tests.jquery-tutorial.net) than the currently executing domain (www.jquery-tutorial.net):

<ul id="ulUsers"></ul>
<script type="text/javascript">
$(function()
{
    $.get
	(
		"http://tests.jquery-tutorial.net/json.php?callback=?", 
		function(data, textStatus)
        {
        	$.each(data, function(index, user)
			{
				$("#ulUsers").append($("<li></li>").text(user.name + " is " + user.age + " years old"));
			});
        },
		"json"
	);		
});
</script>

If you read the chapter on the get() and post() methods, you will see that there are only two main differences: The callback parameter on the URL, and the extra parameter specifying that we want the return type to be "json". The callback is set to a question mark, which will make jQuery generate a random one for us. In the script that takes the call, the value of this parameter is used, as you can see in the PHP code above.

Once we get some data back, we throw it into the each() method, which will loop over the data, each time invoking an anonymous method where we access the current set of data in the "user" variable. We then use the name and age of the user to construct a text representation, which we append to a list (ul tag) as a list item (li tag). As a result, we get an HTML list of the users returned by the script.