【问题标题】:Passing string through ajax function to the page where it gets echoed, PHP, AJAX, JAVASCRIPT通过ajax函数将字符串传递到它被回显的页面,PHP,AJAX,JAVASCRIPT
【发布时间】:2015-07-22 01:59:45
【问题描述】:

我有三个文件。 test1.php、test2.php 和 ajax.php。在 test1.php 中,我有一个文本输入。当我在文本输入中键入内容时,它会调用 ajax 函数,并将我在文本输入中键入的任何内容作为 POST 传递给 test2.php。在 text2.php 中回显后,它显示在 test1.php 中的文本输入下方。

现在,我想在回显之前通过 ajax 函数 将字符串传递给 test2.php,因此它会显示在 test1.php 中的文本输入下方。例如,我想通过 ajax 函数将单词“Hello”传递给 test2.php - 我怎么能做到这一点,或者这甚至可能吗?谢谢你。

test1.php

<?php

include('ajax.php');

echo "<input type = 'text' name = 'text' onkeyup = 'ajax(\"test2.php\",\"input\",\"text\",\"output\")'>";
echo "<div id = 'output'/>";

?>

test2.php

<?php

$text = $_POST['text'];
echo $text;

?>

ajax.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript"> 

function ajax(gotoUrl,type,inputName,output) {

      $.ajax({
           type: "POST",
           url: gotoUrl,
           data: { select: $(type+'[name='+inputName+']').val()},
           error: function(xhr,status,error){alert(error);},
           success:function(data) {
             document.getElementById( output ).innerHTML = data;
           }

      });

}

</script>

【问题讨论】:

  • 我已经阅读了大约 5 次,但我不明白你的问题是什么或你想要做什么......
  • @DaveChen 我想在回显之前通过 ajax 函数将一个字符串传递给 test2.php,所以它会显示在 test1.php 中的文本输入下方。通过ajax函数,而不是通过文本输入。
  • @DaveChen 代码本身没有问题。我只是将它用作 ajax 函数可以做什么的示例。我的实际问题在第二段。
  • @Rasclatt 我想在回显之前通过 ajax 函数将字符串传递给 test2.php,因此它会显示在 test1.php 中的文本输入下方。通过ajax函数,而不是通过文本输入。
  • 所以你有使用keyup输入的ajax,但是你想让它使用字符串作为函数的参数之一自动加载(或以某种方式触发)?

标签: javascript php jquery ajax parameters


【解决方案1】:

这是很有可能的。

在 ajax.php 中: 将新元素添加到您的 data:{} 数组中:

data: { select: $(type+'[name='+inputName+']').val(), some_string: 'Hello' },

在 test2.php 中:您现在可以引用从您的 ajax 请求发送的第二个元素:

<?php

$text = $_POST['select'];
$some_string = $_POST['some_string'];
echo $some_string.$text;

?>

【讨论】:

  • 顺便说一句,text1.php 需要一个结束 &lt;/div&gt; 标记。 :)
  • 是的!这正是我想要的!我很高兴有人能理解我的要求!你太棒了,伙计! ;P
  • @DaveChen 很生气,因为他的答案是错误的,将其删除,并否决了我。哇,哇。
  • 我点赞了它,它应该得到更多点赞,因为对于那些使用 XMLHttpRequest 的人来说,这是一个非常强大和重要的 javascript 概念,它可能会在未来帮助其他用户。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 2013-09-01
  • 1970-01-01
  • 2011-02-12
相关资源
最近更新 更多