[英]Can't pass my Javascript variable to PHP using AJAX
i've a problem with passing my Javascript variable to PHP using AJAX. My $remove
can't echo out when clicking the button.我在使用 AJAX 将我的 Javascript 变量传递给 PHP 时遇到问题。单击按钮时,我的
$remove
无法回显。
HTML Code: HTML 代码:
<p><button class="btn-remove">Remove</button></p>
JavaScript Code: JavaScript 代码:
const removeBtn = document.querySelectorAll('.btn-remove');
removeBtn.forEach((item) => {
item.addEventListener('click', function() {
const toBeRemovedName = item.parentNode.parentNode.children[0].innerHTML;
$.ajax({
url: "./shopping_cart.php",
method: "POST",
data: {toBeRemovedName: toBeRemovedName},
});
})
})
PHP Code: PHP 代码:
if(isset($_POST['toBeRemovedName'])) {
$remove = $_POST['toBeRemovedName'];
echo $remove;
}
The purpose of Ajax is to make an HTTP request with JS and handle the response with JS . Ajax 的作用是用 JS 发起 HTTP 请求,用 JS处理响应。
You aren't doing anything to look at the data that is echoed.您没有做任何事情来查看回显的数据。
jQuery.ajax({ url: "https://cors-anywhere.herokuapp.com/https://postman-echo.com/post", method: "post", data: { example: 12345 } }).then(response => console.log(response));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If you want to navigate to a new page, then submit a <form>
.如果您想导航到新页面,请提交
<form>
。 Don't use Ajax.不要使用 Ajax。
Why not make a normal AJAX request with javascript instead and then you'd use the variable you are trying to pass as a query parameter instead.为什么不使用 javascript 发出正常的 AJAX 请求,然后使用您尝试传递的变量作为查询参数。 For example,
例如,
const removeBtn = document.querySelectorAll('.btn-remove');
removeBtn.forEach((item) => {
item.addEventListener('click', function() {
const toBeRemovedName = item.parentNode.parentNode.children[0].innerHTML;
$.ajax({
url: "./shopping_cart.php?toBeRemovedName=" + toBeRemovedName,
method: "GET"
});
})
})
Then your php code will look like this.那么您的 php 代码将如下所示。
if(isset($_GET['toBeRemovedName'])) {
$remove = $_GET['toBeRemovedName'];
echo $remove;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.