[英]php not showing variable from AJAX
我正在嘗試將變量從javascript發布到同一php頁面。 這是代碼:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
</head>
<body>
<?php echo 'Result is '; if (isset($_GET['testing'])) { echo $_GET['testing']; } ?>
<?php $thisPage = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>
<script>
$(document).ready(function() {
$('#testing123').on('change',function () {
var testing = "confirmed";
$.ajax({
type: "GET",
url: "<?php echo $thisPage; ?>",
data: testing,
success: function() { $('#showresult').html("success"); }
})
});
});
</script>
<form>
<select id="testing123">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
<div id="showresult"></div>
</body>
</html>
我也嘗試過使用POST,但沒有在php中接聽。 還嘗試過使用單獨的php文件並使用include_once()仍然無法正常工作。
我是否缺少要加載的文件?
問題在於您要發送的字符串不是鍵值對。 您可以發送一個字符串(無論如何在屏幕后面都會發生),但是它必須是一個有效的查詢字符串,其中包含正確編碼的鍵-值對。
發送對象更容易,讓jQuery處理編碼:
$('#testing123').on('change',function () {
var testing = "confirmed";
$.ajax({
type: "GET",
url: "<?php echo $thisPage; ?>",
data: testing,
success: function() { $('#showresult').html("success"); }
})
});
會變成這樣:
$('#testing123').on('change',function () {
// send key - value pairs
var testing = {'testing': "confirmed"};
$.ajax({
type: "GET",
url: "<?php echo $thisPage; ?>",
data: testing,
success: function() { $('#showresult').html("success"); }
})
});
編輯:要使您的php腳本的結果返回頁面,您需要使用傳遞給success
函數的變量:
...
success: function(output_from_php_script) {
$('#showresult').text(output_from_php_script);
}
還要注意,在ajax調用中發布到生成該頁面的原始頁面並不是很方便:它將返回您不需要的html負載(整個頁面...)。
您最好編寫一個單獨的腳本來處理您的ajax調用,並僅根據需要返回( echo
...)。
url: "page.php"
我建議您做的是創建一個單獨的php頁面,該頁面僅包含<?php echo 'Result is '; if (isset($_GET['testing'])) { echo $_GET['testing']; } ?>
<?php echo 'Result is '; if (isset($_GET['testing'])) { echo $_GET['testing']; } ?>
<?php echo 'Result is '; if (isset($_GET['testing'])) { echo $_GET['testing']; } ?>
然后使用ajax調用此頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.