2015-04-22 15 views
-1

我在我的php頁面中有一個變量,它是在該頁面上打印的URL,我有另一個html頁面,我需要該php頁面的這個URL值,它應該被賦值到html頁面中的按鈕。 它如何執行?從php到javascript的不同頁面的可變通信

php page content:  
if ($output== true) { 
    //Output results as URL 
    print_r($resulta); 
} 
html page content: 
<p align="center"> 
<input type="button" name="res1" value="result"> 
+8

發佈你有什麼試過! –

+0

使用Ajax調用以訪問php變量。 –

回答

1

使用$ _GET方法在PHP頁面之間傳遞變量。 在你的PHP頁面,

<?php 
     $value = "Some value"; 
     header("location:nextPage.php?variable=$value"); 
     exit(); 
?> 

在nextPage.php

<?php 
     $received = $_GET['variable']; 
?> 

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Title of the document</title> 
</head> 

<body> 
<<button type="button"><?php echo $received; ?></button> 
</body> 

</html>  

如果下一個頁面是不是一個PHP文件,這裏是一個解決方案,

// THIS WORKS FOR MULTIPLE VALUES, BUT IF YOU DO NOT SEND ANY VALUES, IT WILL SHOW ERROR OF "UNDEFINED". BUT THAT CAN ALSO BE FIXED. 
// EXAMPLE : http://yourdomain.com?tag1=100&tag2=200&tag3=300 



<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Title of the document</title> 
<script> 
var url,url_contents,received_values,passed_values; 
url = document.URL; 
url_contents = url.split("?"); 
received_values = url_contents[1]; 
received_values = received_values.split("&"); 
for(var i=0;i<received_values.length;i++) 
{ 
var value_array = received_values[i].split("="); 
alert(value_array[0]+"="+value_array[1]); 
} 

</script> 
</head> 

<body> 

</body> 

</html> 
+0

nextPage不是一個php頁面。那麼,HTML頁面的代碼有沒有改變? –

+0

據我所知,沒有直接的方法,但可以使用間接方法。等等..我會編寫腳本並更新答案。 –

+0

我已經更新了答案,請檢查它。一旦你得到這些值,就不難將它傳遞給佈局元素。 –

2

您應該使用阿賈克斯。
當您需要在HTML頁面中填寫信息時,唯一簡單的方法就是使用Ajax。 我建議你爲更簡單的請求使用jQuery。 https://api.jquery.com/jquery.get/

例:

$(function() { 
 

 
$.get('request.php', {}, function(response) { 
 
    if (response.url) { 
 
    alert('No information from server!'); 
 
    return; 
 
    } 
 
    
 
    $('button.mybutton').onclick(function() { 
 
    window.location.href = response.url; 
 
    }); 
 
}); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button class="mybutton">Click</button>

而在你的PHP是這樣的:

header('Content-Type: application/json'); 
header('Access-Control-Allow-Origin: *'); 
$response = json_encode(array('url' => $url)); 
die($response); 

頁眉「有關使GET請求使用jQuery

更多信息AC當您執行來自不同域的Ajax請求時,「cess-Control-Allow-Origin」非常重要。你可以在谷歌看到更多的用法:Access-Control-Allow-Origin

相關問題