urlencode.php
<?php $name=$_POST['name']; $age = $_POST['age']; $array = array("name"=>$name,"age"=>$age); $result = json_encode($array); echo ($result); ?>
demo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> var xhr = new window.XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.status == 200 && xhr.readyState == 4){ var result = xhr.responseText; result = JSON.parse(result); console.log(result); } } xhr.open("post","./php/urlencode.php",true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send("name=pmx&age=20"); </script> </body> </html>
結果
通常我們使用XMLHttpRequest請求php獲取數據。但是請求的對象僅限於相同域內,對於不同域的請求,我們得使用jsonp技術
jsonp.php
<?php $func = $_GET['jsonc']; $json_data = "'pan',30"; echo $func."(".$json_data.")"; ?>
demo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script> function callback_pmx(name,age) { console.log(name,age); } </script> <script src="./php/jsonp.php?jsonc=callback_pmx"></script> </head> <body> </body> </html>
結果:
1.在script中以get請求php文件,jsonp.php通過$_GET對象獲得了傳給php的參數callback_pmx,這個參數值是一段字符串,和js中預定義好的函數同名。
2.php返回函數執行的字符串表現形式,js得到后,執行這段函數
jsonp.php返回的是一段字符串,這段字符串是函數執行的字符串形式