[英]Trying to send js variables to a php file
當用戶在主php頁面上單擊“完成”時,我試圖將js變量從我的js文件發送到另一個php文件。 到目前為止,這是我的代碼:
map.php
<form action="./finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
map.js
function sendData() {
$.ajax({
method: "POST",
url: "../finalmap.php",
data: {
selectedLoc: selectionArray,
startLoc: start,
endLoc: end,
dist: distance,
locTypes: allLocations
},
beforeSend : function(http) { },
success : function(response,status,http) {
alert(response);
},
error : function(http,status,error) {
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
});
}
finalmap.php
<?php
$data = $_POST['data'];
echo $data;
?>
發布成功,我可以從alert命令中看到finalmap.php中的內容(我的代碼)。 當我嘗試在finalmap.php中console.log $data
時,它為空/空。
我的目標是將數據發送到finalmap.php並重定向到它。
./finalmap.php不是問題。
相反,代碼必須如下所示:
<form action="/finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
嘗試改用它。
編輯:對不起,我只是封住並粘貼。
要解決此問題,您必須一次將測試內容簡化為一件事。 您的代碼有錯誤,並且不完整。 因此,讓我們首先從錯誤開始:如果使用的是AJAX,則不希望HTML以常規方式提交表單。 如果刷新頁面,則您的AJAX無法正常工作。
<button type="button" id="submit-button">FINISH</button>
注意,不需要<form>
; 您正在通過AJAX提交。
接下來,您需要確保您的ajax函數正在執行(因為您正在使用$.ajax
,所以我假設您已加載了JQuery):
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
// this is the same idea as your onclick="sendData();
// but this separates the javascript from the html
$('#submit-button').on('click', function() {
console.log('hello world');
});
});
</script>
您使用Web控制台查看console.log消息。
現在,通過一個簡單的文章嘗試使用ajax命令:
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
$('#submit-button').on('click', function() {
$.ajax({
method: "POST",
// "./finalmap.php" or "../finalmap.php"?
url: "../finalmap.php",
data: {foo: 'bar'},
success: function(response){
console.log('response is: ');
console.log(response);
}
});
});
});
</script>
<?php echo 'This is finalmap.php';
如果在按下按鈕后在Web控制台中看到This is finalmap.php
,則可以嘗試發送數據。
<?php
echo 'You sent the following data: ';
print_r($_POST);
看看我們要怎么做? 吃大象的方式一次只能咬一口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.