本文目錄一覽:
AJAX 向PHP傳遞參數
能啊!給你個例子啊!
html
head
script type=”text/javascript”
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// all modern browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// for IE5, IE6
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open(“GET”,url,true);
xmlhttp.send(null);
}
else
{
alert(“Your browser does not support XMLHTTP.”);
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = “loaded”
if (xmlhttp.status==200)
{// 200 = “OK”
document.getElementById(‘p1’).innerHTML=”This file was last modified on: ” + xmlhttp.getResponseHeader(‘Last-Modified’);
}
else
{
alert(“Problem retrieving data:” + xmlhttp.statusText);
}
}
}
/script
/head
body
p id=”p1″
The getResponseHeader() function returns a header from a resource.
Headers contain file information like length,
server-type, content-type, date-modified, etc./p
button onclick=”loadXMLDoc(‘/example/ajax/test_xmlhttp.txt’)”Get “Last-Modified”/button
/body
/html
如何在同一個PHP頁面,通過ajax把值傳給PHP變量?
舉個例子:你想在用戶點擊時,把 apple 這個字符串,通過前端傳給後端。
前端,用 jQuery 舉例:
$(‘button’).click(function () {
$.ajax({
url: ‘/xxx’,
method: ‘post’,
dataType: ‘json’,
data: {fruit: ‘apple’}
}).done(function (res) {
// 成功後的回調
}).fail(function (err) {
// 失敗後的回調
});
});
後端 PHP 處理:
$fruit = $_POST[‘fruit’]; // 獲取從 ajax 傳過來的 fruit 的值,這裡是 apple。
如果你想在前端重新顯示這個字符串 apple,那麼你要用 PHP 把數據返回給頁面,然後在上面 「// 成功後的回調」 裏面,補充邏輯代碼。
例如 PHP 把 apple 返回給前端:
return json_encode(array(‘fruit’ = ‘apple’));
前端回調處理:
// 成功後的回調
alert(res.fruit); // 彈框顯示 「apple」
實際上,$_POST 能夠獲取所有從前端用 post 方式提交過來的數據,不管你是頁面刷新方式,還是 ajax(jQuery 才叫 ajax,實際上它是 XMLHttpRequest,異步非阻塞的請求方式)
ajax 如何 傳參數給php文件?
首先var btnfct1 = 1;不是這樣定義的,
xmlHttp.send(btnfct1); //有參數要提交
這裡btnfct1必須是對象,如{‘btnfct1’:1}
然後在php端$_POST[‘btnfct1’]就能取到值了
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/292021.html