> For the complete documentation index, see [llms.txt](https://javascriptuse.gitbook.io/advanced/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://javascriptuse.gitbook.io/advanced/4.-javascript-tao-script-dong-va-ki-thuat-jsonp-ok.md).

# 4. Javascript – Tạo script động và kĩ thuật JSONP (ok)

Ví dụ:

C:\xampp\htdocs\hanoi.com\index.php

```
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript" src="http://localhost/library/jquery/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
    $("#button1").click(function() {
      var empId=$("#empId").val();
      $.getJSON("http://hanoi.com/test.php?callback=?","id="+empId, function(data){
          document.getElementById("info").innerHTML="Id = " + data.Id + "<br/>Name = " + data.Name;
      });
    });
});
</script>
Employee Id:
<br/>
<input type="text" id="empId"></input>
<button id="button1">Get Info</button>
<br/>
Info:
<br/>
<div style="border:1px solid black;width:240px;height:100px" id="info"></div>
</body>
</html>
```

C:\xampp\htdocs\hanoi.com\test.php

```
<?php
	$employees = array("Ethan", "Matt", "Daniel", "Kristoffer", "Markus");
	$callback  = "";
	$id        = 0;
	if (isset($_GET["callback"])) {
	  $callback = $_GET["callback"];
	}
	if (isset($_GET["id"])) {
	  $id = $_GET["id"];
	}

	$response = array(
	  "Id"   => $id,
	  "Name" => $employees[$id],
	);
	echo $callback . "(" . json_encode($response) . ");";
?>
```

## [Javascript – Tạo script động và kĩ thuật JSONP](https://yinyangit.wordpress.com/2011/12/28/javascript-tao-script-dong-va-ki-thuat-jsonp/)

JSONP là viết tắt của **Json with padding**, đây là kĩ thuật thêm các thẻ \<script> động trong quá trình trang web làm việc, kết hợp với dữ liệu lấy từ server để tạo lời gọi callback khi dữ liệu được tải xong. Việc này giống như việc bạn có thể truyền một hàm từ client đến server. Đây ko phải là Ajax mà chỉ là việc nạp động một đoạn mã javascript từ xa. Đoạn mã này chứa một lời gọi hàm từ chính trang hiện tại và với tham số là dữ liệu json được lấy từ server.

![Client JSONP Request Example](https://yinyangit.files.wordpress.com/2011/12/client-jsonp-request-example.png?w=150\&h=112)

### Server

Trong ví dụ này, tôi sẽ tạo server với ngôn ngữ PHP. Server sẽ nhận một chuỗi query string chứa hai tham số là tên của hàm callback và employee id để lấy thông tin của nhân viên.

```
<?php
    $employees = array("Ethan","Matt","Daniel","Kristoffer","Markus");
    // get the callback function name, id from query string
    $callback = "";
    $id=0;
    if (isset($_GET["callback"]))
    {
        $callback = $_GET["callback"];
    }
    if (isset($_GET["id"]))
    {
        $id= $_GET["id"];
    }
 
    $response = array(
          "Id" => $id,
          "Name" =>   $employees[$id]
    );
    echo $callback . "(".json_encode($response).");";
    // return example: functionName({"Id":0,"Name":"Ethan"});
```

Server: PHP

### Client

Tại phía client, tôi sẽ dùng javascript để thêm động một thẻ \<script> vào trang với thuộc tính src là địa chỉ tới server. Từ địa chỉ này, nội dung bên trong thẻ script sẽ là nội dung mà server trả về. Như trong ví dụ ở đoạn mã trên, nó chính là một lời gọi hàm javascript. Hàm này đã được tạo sẵn ở client.

```
<html><head></head>
<body>
<script type="text/javascript">
    function callJsonpRequest(callbackName)
    {
        var empId=document.getElementById("empId").value;
 
        var head = document.getElementsByTagName("head")[0];
        var script = document.createElement("script");
        script.src = "http://localhost/Test/test.php?callback="+callbackName+"&id="+empId;
 
        head.appendChild(script);
    }
 
    function receiveResponse(data)
    {
        document.getElementById("info").innerHTML="Id = " + data.Id + "<br/>Name = " + data.Name;
    }
</script>
Employee Id:
<br/>
<input type="text" id="empId"></input>
<button  id="button1" onclick="callJsonpRequest('receiveResponse')">Get Info</button>
<br/>
Info:
<br/>
<div style="border:1px solid black;width:240px;height:100px" id="info"></div>
</body>
</html>
```

Trong tập tin html sau, tôi sẽ sử dụng hàm **callJsonpRequest**() để tạo thẻ \<script> động và dùng hàm **receiveResponse**() để làm hàm callback gửi đến server.

### JSONP và jQuery

jQuery cung cấp phương thức [**$.getJSON()**](http://api.jquery.com/jQuery.getJSON/) giúp bạn lấy được dữ liệu json thông qua một request HTTP. Vì phương thức này sử dụng hàm .ajax() và cần đến đối tượng `XMLHTTPRequest` nên đây chính là phương pháp sử dụng ajax.

Bạn thực hiện một request jsonp bằng cách thêm tham số **callback=?** vào sau url của server. jQuery sẽ tự động tạo ra tên phương thức với nội dung là hàm callback mà bạn truyền vào làm tham số **success** cuối cùng của hàm.

Đoạn mã client ở phần trên có thể được viết lại như sau:

Minh họa:

\
[https://yinyangit.wordpress.com](https://yinyangit.wordpress.com/)

![Client JSONP Request Example](https://yinyangit.files.wordpress.com/2011/12/client-jsonp-request-example.png?w=620)

#### Bình chọn


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/advanced/4.-javascript-tao-script-dong-va-ki-thuat-jsonp-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
