[英]Can not see the value of php variable
我有一個php文件,單擊按鈕后從哪里運行save_match()
:
function save_match() {
...
$.post('url2', {elements: elements});
...
}
並運行另一個php文件,其中包含以下內容:
<?php
$tok = 1024;
if($_POST['elements'])
{
echo '<script>foo("'.$tok.'") </script>';
...
?>
<html>
<body>
<script type="text/javascript">
function foo(p1) {
//alert(p1);
document.write("|"+p1+"|");
}
</script>
</body>
</html>
我這樣做的原因是,由於echo
我什么都看不到。 好吧,現在我看到了更多。
我也在新標簽頁中打開了url2
。 但是,在按url1中的按鈕並轉到第二個url的選項卡后,沒有任何更改。 我刷新了,但是什么都沒有改變!
我能做什么? 我需要這個來進行調試。
您可以執行以下操作來查看令牌的值。
將您的代碼更改為關注。
<?php if (isset($_POST['elements'] && $_POST['elements'])) echo $tok; .....
將您的JavaScript更新為:
function save_match() { ... $.post('url2', {elements: elements}, function($token) { console.log($token); // will print your token in javascript console }); ... }
<html>
<body>
<?php
$tok = 1024;
if(isset($_POST['elements']))
{
echo $tok;
}
?>
</body>
</html>
這應該工作。 確保設置了doctype以及所有其他文檔,並且還設置了POST中的變量元素。 也許if函數總是會失敗,因為沒有設置任何元素。
對於您嘗試做的事情,您實際上不需要JavaScript。
等待異步動作的函數示例:
function save_match(){
var somethingToReturn, pushTo = [];
$.post('url2.php', {saveMatch:1, simple:'column_value_here', anotherProp:'Example'}, function(phpComesBackHere){
$.each(phpComesBackHere, function(i, o){
pushTo.push(o.object_property);
});
somethingToReturn = pushTo;
});
while(1){
if(somethingToReturn){
return somethingToReturn;
}
}
}
在url2.php上,它像:
<?php
include 'secure_database_connection.php'; $db = db(); // function db is returning `new mysqli('host', 'username', 'password', 'database');`
if(isset($_POST['saveMatch'])){
if(+$_POST['saveMatch'] === 1){
if(isset($_POST['simple'], $_POST['anotherProp'])){
if($qry = $db->query("SELECT * FROM table_name WHERE column={$_POST['simple']}")){
if($qry->num_rows > 0){
while($r = $qry->fetch_object()){
$returnArray[] = array('object_property' => $r->your_property_here, 'anotherProp' => $r->and_another_property);
}
echo json_encode($returnArray);
}
$qry->free();
}
}
else{
// simple and/or anotherProp hack
}
}
else{
// saveMatch hack
}
}
elseif(isset($_POST['somethingElse'])){
// this could be separate $.post on same page
}
$db->close();
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.