我有一个带有三个参数的ajax函数。第一个参数保存 ajax 函数被调用时转到的 url。第二个参数包含包含最终输出的 div 的 id 名称。第三个参数包含一个变量,可以存储在POST中,发送到ajax函数调用时转到的url,这样就可以回显,并发送到原始页面上id为“output”的div 。
我的问题是:有没有办法获取输入类型submit中的值,以便可以将其存储在POST中发送到ajax函数调用时所去的url,以便可以回显,并在原始页面上的 id 为“output”的 div 中看到?
因此输入类型提交中的值将是“submit”。
test1.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajaxPass(gotoUrl,output,input) {
$.ajax({
type: "POST",
url: gotoUrl,
data: { input : input },
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
}
});
}
</script>
<input type = "submit" name = "submit" value = "submit" onclick = "ajaxPass('test2.php','output','input')">
<div id = 'output'> </div>
test2.php
<?php
$input = $_POST['input'];
echo $input;
?>
最佳答案
不确定我是否理解,但我会尝试回答这部分:
Are there any ways to get the value in the input type submit
<input type = "submit" name = "submit" value = "submit" onclick = "ajaxPass('test2.php','output',this.value)">
关键是使用 this.value
,this
引用输入元素,而 value
当然是它的值。
查看这个简单的示例以了解其实际效果:
<input type = "submit" name = "submit" value = "submit value here" onclick = "alert(this.value)">
更新
此示例将读取文本输入元素的值并将其作为 AJAX 调用中的 input
变量传递:
function ajaxPass(gotoUrl,output) {
var input = document.getElementById('t').value; // or $('#t').val();
$.ajax({
type: "POST",
url: gotoUrl,
data: { input : input },
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
}
});
}
</script>
<input type="text" id="t">
<input type = "submit" name = "submit" value = "submit" onclick = "ajaxPass('test2.php','output')">
<div id = 'output'> </div>
关于javascript - 通过AJAX、PHP获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31822638/