JSONP, alanlar arası sorunlar hakkında endişelenmeden JSON verilerini göndermeye yönelik bir yöntemdir.
JSONP, XMLHttpRequest nesnesini kullanmaz.
JSONP bunun yerine <script> etiketini kullanır.
JSONP, Dolgulu JSON anlamına gelir.
Başka bir alan adından dosya istemek, alanlar arası politika nedeniyle sorunlara neden olabilir.
Başka bir alan adından harici bir komut dosyası talep edildiğinde bu sorun yaşanmaz.
JSONP bu avantajı kullanır ve dosyaları script etiketini kullanarak ister XMLHttpRequest nesnesi yerine.
<script src="demo_jsonp.php">Sunucudaki dosya, sonucu bir dosyanın içine sarar. işlev çağrısı:
<?php
$myJSON = '{ "name":"John", "age":30, "city":"New York" }';
echo "myFunc(".$myJSON.");";
?>Sonuç, JSON verileriyle birlikte "myFunc" adlı bir işleve yapılan çağrıyı döndürür: bir parametre.
İşlevin istemcide mevcut olduğundan emin olun.
"myFunc" adlı işlev istemcide bulunur ve kullanılmaya hazırdır JSON verileri:
function myFunc(myObj)
{
document.getElementById("demo").innerHTML =
myObj.name;
}Kendiniz Deneyin →
<!DOCTYPE html>
<html>
<body>
<h2>Request JSON using the script tag</h2>
<p>The PHP file returns a call to a function that will handle the JSON data.</p>
<p id="demo"></p>
<script>
function myFunc(myObj) {
document.getElementById("demo").innerHTML = myObj.name;
}
</script>
<script src="demo_jsonp.php"></script>
</body>
</html>
Yukarıdaki örnek, sayfa açıldığında "myFunc" fonksiyonunu çalıştıracaktır. script etiketini nereye koyduğunuza bağlı olarak yükleme, bu pek tatmin edici değil.
Komut dosyası etiketi yalnızca gerektiğinde oluşturulmalıdır:
Bir düğmeye tıklandığında <script> etiketini oluşturun ve ekleyin:
function clickButton() {
let s = document.createElement("script");
s.src = "demo_jsonp.php";
document.body.appendChild(s);
}Kendiniz Deneyin →
<!DOCTYPE html>
<html>
<body>
<h2>Click the Button.</h2>
<p>A script tag with a src attribute is created and placed in the document.</p>
<p>The PHP file returns a call to a function with the JSON object as a parameter.</p>
<button onclick="clickButton()">Click me!</button>
<p id="demo"></p>
<script>
function clickButton() {
let s = document.createElement("script");
s.src = "demo_jsonp.php";
document.body.appendChild(s);
}
function myFunc(myObj) {
document.getElementById("demo").innerHTML = myObj.name;
}
</script>
</body>
</html>
Yukarıdaki örnekler hala oldukça statiktir.
JSON'u php dosyasına göndererek örneği dinamik hale getirin ve php dosyasının aşağıdakileri temel alan bir JSON nesnesi döndürmesine izin verin: aldığı bilgi.
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj =
json_decode($_GET["x"], false);
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM
".$obj->$table." LIMIT ".$obj->$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo "myFunc(".json_encode($outp).")";
?>İsteği PHP işlevini kullanarak bir nesneye dönüştürün json_decode().
Veritabanına erişin ve bir diziyi istenen verilerle doldurun.
Diziyi bir nesneye ekleyin.
Diziyi kullanarak JSON'a dönüştürün json_encode() işlevi.
"myFunc()" ifadesini dönüş nesnesinin etrafına sarın.
"myFunc" işlevi php dosyasından çağrılacaktır:
const obj = { table: "products", limit: 10 };
let s = document.createElement("script");
s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj);
document.body.appendChild(s);
function myFunc(myObj) {
let txt = "";
for (let x in myObj)
{
txt += myObj[x].name + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}Kendiniz Deneyin →
<!DOCTYPE html>
<html>
<body>
<p>A script tag with a src attribute is created and placed in the document.</p>
<p>The PHP file returns a call to a function with an object as a parameter.</p>
<p id="demo"></p>
<p>Try changing the table property from "customers" to "products".</p>
<script>
const obj = { table: "customers", limit: 10 };
let s = document.createElement("script");
s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj);
document.body.appendChild(s);
function myFunc(myObj) {
let txt = "";
for (let x in myObj) {
txt += myObj[x].name + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Sunucu dosyası üzerinde hiçbir kontrolünüz olmadığında sunucu dosyasını nasıl alırsınız? doğru işlevi çağırmak için?
Bazen sunucu dosyası aşağıdaki gibi bir geri arama işlevi sunar: bir parametre:
Php dosyası, geri çağırma parametresi olarak ilettiğiniz işlevi çağıracaktır:
let s = document.createElement("script");
s.src = "jsonp_demo_db.php?callback=myDisplayFunction";
document.body.appendChild(s);Kendiniz Deneyin →
<!DOCTYPE html>
<html>
<body>
<h2>Request With a Callback Function</h2>
<p>The PHP file returns a call to the function you send as a callback.</p>
<p id="demo"></p>
<script>
let s = document.createElement("script");
s.src = "demo_jsonp2.php?callback=myDisplayFunction";
document.body.appendChild(s);
function myDisplayFunction(myObj) {
document.getElementById("demo").innerHTML = myObj.name;
}
</script>
</body>
</html>