javascript 使用ajax post使用ajax传递php值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18088119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass php value with ajax with ajax post
提问by MathieuB
I'm using an ajax script to post a value to a PHP file. I'm not able to pass the variable.
我正在使用 ajax 脚本将值发布到 PHP 文件。我无法传递变量。
My variable is declared in PHP and I would like to pass it with ajax.
我的变量是用 PHP 声明的,我想用 ajax 传递它。
Here is the variable and my button:
这是变量和我的按钮:
<?php $employee_id= '3'; ?>
<input class="btn btn-danger" type="submit" value="Delete" id="delete-btn">
This is the Javascript:
这是Javascript:
<script>
$(document).ready(function () {
$("input#delete-btn").click(function(){
$.ajax({
type: "POST",
url: "delete.php", //
data: {id: '$employee_id'},
success: function(msg){
$("#thanks").html(msg)
},
error: function(){
alert("failure");
}
});
});
});
</script>
Here is the PHP code where I want to receive the value:
这是我想要接收值的 PHP 代码:
if (isset($_POST['id'])) {
$emp_id = strip_tags($_POST['id']);
echo $emp_id;
$query = "DELETE FROM `employee` WHERE id='$emp_id'";
$result = mysql_query($query) OR die(mysql_error());
echo 'You successfully deleted the user.';}
I know I'm doing something wrong around the data...
我知道我在数据方面做错了什么......
回答by Lochemage
That is because your variable is in php but you are not using php to attach your variable to your ajax, try wrapping your variable in php tags and then make sure you use 'echo' to print the value of your variable into javascript.
那是因为您的变量在 php 中,但您没有使用 php 将您的变量附加到您的 ajax,请尝试将您的变量包装在 php 标签中,然后确保您使用 'echo' 将您的变量的值打印到 javascript 中。
data: {id: <?php echo '$employee_id'?>},
Your javascript code, as far as the client will see, will end up looking like this for them:
就客户而言,您的 javascript 代码最终将如下所示:
data: {id: '3'},
They won't see the php code, they will just see the end result as their javascript.
他们不会看到 php 代码,他们只会看到最终结果作为他们的 javascript。
回答by jh314
You need PHP tags around your variables:
你的变量周围需要 PHP 标签:
<script>
$(document).ready(function () {
$("input#delete-btn").click(function(){
$.ajax({
type: "POST",
url: "delete.php", //
data: {id: <?php echo '$employee_id'; ?> }, // <---
success: function(msg){
$("#thanks").html(msg)
},
error: function(){
alert("failure");
}
});
});
});
</script>