javascript - 通过AJAX、PHP获取值

标签 javascript php jquery ajax

我有一个带有三个参数的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.valuethis 引用输入元素,而 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/

相关文章:

javascript - 在数组值之间循环

php - laravel 5.3 中未定义路由 [ payment-data ]

javascript - 如何将 Ajax 响应中的值附加到 JavaScript 中的数组?

javascript - 在自定义数据属性中调用函数?

javascript - 根据滚动到的部分设置 url 哈希?

javascript - 在元素数组上 react 事件监听器

php - SQL 错误 : Every derived table must have its own alias

php - 在 joomla 2.5 上使用 jumi 时,include 或 require_once 给出错误

javascript - jQuery UI ui-autocomplete-loading 微调器在找到结果时不停止/消失

javascript - typescript 路由错误 - 没有与此调用匹配的过载