我将数据发送到php有问题。我想通过jquery ajax发送按钮值。这是我的代码: HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
</script>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
PHP:
<?php
$name = $_POST['data'];
echo $name;
?>
它没有工作......
答案 0 :(得分:3)
尝试这一点,我只是做了并且工作得很好
这是我的js文件
<html>
<head>
</head>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
<footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('button').click(function() {
var val = $(this).val();
$.ajax({
// your uri, pay attention if the post is going to the right place
url: "try.php",
type: "POST",
// myVar = name of the var that you will be able to call in php
// val = your data
data: {'myVar': val}
});
});
});
</script>
</footer>
</html>
这是我的PHP
<?php
$name = $_POST['myVar']; //the var you put in your ajax data:{}
print_r($name);
在谷歌浏览器中你可以按f12并转到网络选项卡,你将能够看到你的浏览器所做的请求和他们的回复
答案 1 :(得分:0)
制作适当的json字符串以发送数据。你在这里有额外的;
。
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
在php中使用data
键获取它。
<?php
$name = $_POST['data'];
echo $name;
?>
另外,在document.ready()
内编写您的事件监听器。目前您的监听器未被应用,因为脚本位于顶部,并且无法找到<button>
,因为它们尚未出现。
答案 2 :(得分:0)
<button id="example" name="name_example" value="some_value">
1</button>
$(document).ready(function () {
$('#example').click(function() {
var buttonValue = $(this).val();
$.ajax({
url: "try.php", //assuming that your html file is in the same folder as
//your php script.
type: "POST",
data: {'example': buttonValue}
});
});
});
看看这个:https://jsfiddle.net/willianoliveirac/yarLfdnu/
在.php文件中,该文件应与执行请求的html文件位于同一文件夹中:
<?php
echo '<pre>'; print_r($_POST); die; // see if you now have those vars.
?>