使用AJAX从JavaScript传递变量值到PHP

10
我希望用jQuery/AJAX将一些值从JavaScript传递到PHP。我有以下“简化”的代码,不确定我的错误在哪里。StackOverflow上似乎有很多类似的问题/答案,但是没有一个真正有用。 HTML:
<div>
<a href="#" id="text-id">Send text</a>
<textarea id="source1" name="source1" rows="5" cols="20"></textarea>
<textarea id="source2" name="source2" rows="5" cols="20"></textarea>
</div>

JAVASCRIPT:

$("#text-id").click(function() {
$.ajax({
type: 'post',
url: 'text.php',
data: {source1: "some text", source2: "some text 2"}
});
});

PHP(text.php):

<?php 

$src1= $_POST['source1'];  
$src2= $_POST['source2'];     

echo $src1; 
echo $src2;

?>

问题:什么都没有发生……没有错误……什么都没有。我看不到“source1”和“source2”的值显示在PHP的echo语句中。


1
首先要包含jQuery文件。 - Rituraj ratan
那个已经在HTML头部了,我这里只是没有展示出来。 - Gandalf
1
请给我们一些线索!发生了什么或者没有发生什么?你看到错误信息了吗? - user1864610
请注意更新后的答案POST应该大写。 - Rituraj ratan
好的 - 服务器日志里有什么? - user1864610
2个回答

10

你需要在AJAX调用中包含一个成功处理程序

$("#text-id").on( 'click', function () {
    $.ajax({
        type: 'post',
        url: 'text.php',
        data: {
            source1: "some text",
            source2: "some text 2"
        },
        success: function( data ) {
            console.log( data );
        }
    });
});

在你的控制台中,你会收到:

some textsome text 2

请确保test.php文件和您的HTML源文件位于同一个目录中。


1
嗨,JavaScript控制台确实显示了“some textsome text 2”。但出于某种原因,我没有看到任何PHP echo语句。您能告诉我为什么吗? - Gandalf
@Gandalf 我不确定我理解你的问题。你想要 PHP 源代码被发送回来吗? - hjpotter92
是的...它应该执行某些操作,然后将控制权返回给JavaScript。至少这是我想要实现的。在这种情况下,“echo $src1”语句没有做任何事情。我原以为它会用$src1的值填充页面。 - Gandalf
1
$src1 的值为 some text$src2 的值为 some text 2。它正在填充这些数据。 - hjpotter92

1
$("#text-id").click(function(e) {// because #text-id is an anchor tag so stop its default behaivour
e.preventDefault();
$.ajax({
type: "POST",// see also here
url: 'text.php',// and this path will be proper
data: {
       source1: "some text",
       source2: "some text 2"}
}).done(function( msg )
      {
       alert( "Data Saved: " + msg );// see alert is come or not
     });
});

参考 ajax


谢谢,但这并没有帮助到我。 - Gandalf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接