JS中同步調用PHP函數
1、在JS中創建一個函數,該函數可以發送Http請求到服務端,並受到返回消息,可以使用get或者是post
function HttpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("get", theUrl, false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
function HttpPost(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", theUrl, false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
2、在JS函數中調用PHP
php文件
<?php
$action = $_GET["action"];
switch ($action) {
case "Test": //
sleep(3);//等待時間,測試異步還是同步
echo "調用成功";
break;
?>
調用函數
function Test()
{
var response = HttpGet("php.php?action=Test");
alert(response);
alert("123456");
return;
}
該函數先彈出“調用成功”再彈出”123456“
JS中使用Ajax調用Php
function AjaxHttp(theUrl) {
$.ajax({
type: 'post',
url: theUrl,
success: function (response) {
alert(response);
return response;
},
});
}
使用Ajax進行調用,由於Ajax使用異步調用,所以要在調用後得到結果在進行處理必須要在Ajax中進行處理