跳到主要內容

JS接收ajax.php回傳變數值的簡易方法:徐嘉裕Neil hsu

JS如要接收ajax.php回傳變數值,最常用的方法就是使用dataType: 'json',然後在ajax.php使用陣列方式來傳遞變數,像是下面這樣

$res['1']=123;
$res['2']=456;
echo json_encode($res);exit;

但最近想出一個更簡單的方法來讓js來接收ajax.php回傳變數值,也不需要使用到json,只要吧變數用,串接起來就好了,例如:

$text="".$var1.",".$var2.",".$var3.",".$var4.",".$var5."";

echo $text;

這樣在JS的$.ajax的success: function(response) {}裡面加上

var $response_arr = response.split(','); //切割陣列

$var1=$response_arr[0];

$var2=$response_arr[2];

$var3=$response_arr[3];

$var4=$response_arr[4];

$var5=$response_arr[5];


吧原本串接的5個變數切割成5個列陣,這樣就能輕鬆的接收ajax.php回傳的變數值了,感覺比json好用,有需要的朋友可以參考看看!


教學撰寫:徐嘉裕 Neil hsu

留言