本文目錄一覽:
同一php文件中,如何將Js代碼中的變數,傳遞到php代碼中。
你沒理解 js/php 運行時的順序和邏輯.
js僅在 瀏覽器中運行.
php 僅在伺服器端運行.
2者交互, 通常通過 http get/post 協議進行交互.
因此, 要將 js 變數傳輸到 php, 需通過 get/post 將參數傳入.
譬如:
script
function test(){
var x=”abc”;
$.ajax(“test.php?x=”+x);
}
/script
而 test.php 中, 通過 $_REQUEST[“x”] 即可拿到js 請求過來的變數.
如何將js變數賦值給php
php變數賦值給js就比較容易,如 var aaa=’?php echo $ddd;’;
js變數賦值給php,就得用ajax方式了
$.ajax({
type : “post”,
url : 請求的url 後台php對應的方法處理,
dateType : “json”,
data:{‘變數名1′:變數值1 ,’變數名2’:’變數值2’… },
success : function(data) {
}
});
如何把一個js變數傳給php變數
js僅在 瀏覽器中運行.
php 僅在伺服器端運行.
2者交互, 通常通過 http get/post 協議進行交互.
因此, 要將 js 變數傳輸到 php, 需通過 get/post 將參數傳入.
譬如:
script
function test(){
var x=”abc”;
$.ajax(“test.php?x=”+x);
}
/script
而 test.php 中, 通過 $_REQUEST[“x”] 即可拿到js 請求過來的變數.
追問
感覺你的答案最符合我的需求,只是我還是碰到了問題。
test.php文件中
onchange事件觸發test()函數,並將賦值。
script
function test(){
var x=”abc”;
$.ajax(“test.php?x=”+x);
}
test.php文件中
echo $_REQUEST[“x”]並未獲取到有效值。echo沒有輸出。
請問,這到底是什麼原因。
追答
是因為 script 中並沒有輸出由 php 傳回的結果.
改成這個試試看.
1
2
3
4
5
6
script
function test(){
var x=”abc”;
$.ajax(“test.php?x=”+x),null,function(data){alert(data)});
}
/script
js中var聲明的變數賦給php變數
您好!很高興為您解答:
目測這種情況用ajax;
input type=”button” value=”先傳給php在讓php列印出來” id=”btn”/
script
var btn=document.getElementById(‘btn’);
var a=’123456′;
btn.onclick=function(){
var ajax=new XMLHttpRequest();
ajax.open(‘GET’,’a.php?use=’+a,true)
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
alert(ajax.responseText);
}
}
}
ajax.send();
}
/script
以下是php
?php
$a=$_GET[‘use’];
echo $a;
這樣就把js的變數給了php的變數
望採納
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/194677.html